TheDuncan
TheDuncan

Reputation: 50

Trying to parse JSON data with python

I am having no luck trying to parse this json data, i only care about a small amount of it.

json data

{
    "timestamp" : 1397555135361,
    "sets" : {
        "worldguard.markerset" : {
            "areas" : {
                "world_region_name" : {
                    "markup" : false,
                    "desc" : "What I really want.",
                    "weight" : 3,
                    "color" : "#FF0000",
                    "fillopacity" : 0.35,
                    "opacity" : 0.8,
                    "label" : "Region_name",
                    "ytop" : 65.0,
                    "fillcolor" : "#FF0000",
                    "z" : [846.0, 847.0, 847.0, 846.0],
                    "ybottom" : 65.0,
                    "x" : [773.0, 773.0, 774.0, 774.0]
                }
            }
        }
    }
}

I hope I copied it correctly, it a very large file, and I only care about the region info that it has.

there are other parts of this json file, that I don't care about, so I haven't included them. but there are many items under 'areas' that I do care about. I just cant work out how to parse them all

import json
from pprint import pprint
json_data=open('marker_world.json')

data = json.load(json_data)


for item in data["sets"]["worldguard.markerset"]["areas"]:
    print item

the items that i care about from each region is; desc, label, z, & x .

It doesn't seem to print out the everything under that region like I would expect all I get is a screen of "u'w'"

I haven't even started to try and select only the bits out of each region I care about. A push in the right direction would be great if you can workout what I am doing wrong.

Upvotes: 0

Views: 97

Answers (1)

alecxe
alecxe

Reputation: 473763

Here's what you can start with.

Define a list of keys you need from an area, then iterate over areas, for each area get the values of the keys you've defined:

keys = ['desc', 'label', 'x', 'z']
for area_key, area_items in data["sets"]["worldguard.markerset"]["areas"].iteritems():
    print area_key
    for key in keys:
        print '%s: %s' % (key, area_items[key])

prints:

world_region_name
desc: What I really want.
label: Region_name
x: [773.0, 773.0, 774.0, 774.0]
z: [846.0, 847.0, 847.0, 846.0]

Upvotes: 1

Related Questions