简体   繁体   English

尝试使用python解析JSON数据

[英]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数据,我只关心其中的一小部分。

json data json资料

{
    "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. 这个json文件的其他部分我也不在乎,因此没有包括在内。 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 . 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'" 似乎并没有打印出该区域下的所有内容,就像我希望得到的只是一个屏幕“ 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. 如果您可以锻炼我做错的事情,朝着正确的方向努力将是很好的。

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: 定义一个区域所需的键列表,然后遍历areas ,为每个区域获取已定义键的值:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM