python确定json属性

时间:2017-05-02 16:21:45

标签: python

我想以JSON格式确定每个属性,我不知道JSON文件的内容。

例如,我有这些不同的文件:

[
{
    "name": "abc",
    "hobby": "swimming"
},
{
    "name": "xyz",
    "hobby": "programming"
}
]

和第二个例子:

[
{
    "street": "PL EDOUARD BOUILLIERE",
    "nb_places_totales": 249
},
{
    "street": "CHE DU VERDON",
    "nb_places_totales": 212
}
]

如何使用python解析和确定属性名称?

4 个答案:

答案 0 :(得分:1)

使用json包解析文件。然后,您可以查看数据结构中第一项的键。

import json

with open(filename) as fid:
    data = json.load(fid)

print(data[0].keys())

答案 1 :(得分:0)

data = """[
{
    "name": "abc",
    "hobby": "swimming"
},
{
    "name": "xyz",
    "hobby": "programming"
}
]"""

import json
d = json.loads(data) # here I am loading from the string, but you can load from a json file by using json.load() instead of json.loads()

 # iterate through the list of dicts and print the keys for each dict
for _ in d:
    print _.keys()

这将导致:

[u'hobby', u'name']
[u'hobby', u'name']

答案 2 :(得分:0)

您需要在python3中检查字典键:

import json

a = json.loads("""
[{"name": "abc", "hobby": "swimming" },
{"name": "xyz", "hobby": "programming"}]
""")

b = json.loads("""
[{"street": "PL EDOUARD BOUILLIERE", "nb_places_totales": 249},
{"street": "CHE DU VERDON", "nb_places_totales": 212 }]
""")

print(*(i.keys() for i in a))
print(*(i.keys() for i in b))

但无论如何,每个解决方案都会以某种方式依赖内容。

答案 3 :(得分:-2)

这是获取属性名称的方法。如果您想要值,则打印值而不是键。

import json
import sys

obj1 = [
{
    "name": "abc",
    "hobby": "swimming"
},
{
    "man": "xyz",
    "hobby": "programming"
}
]

obj2 = [
{
    "street": "PL EDOUARD BOUILLIERE",
    "nb_places_totales": 249
},
{
    "street": "CHE DU VERDON",
    "nb_places_totales": 212
}
]

print "Obj1 Attributes"
for i in range(0, len(obj1)):
    for key, value in obj1[i].items():
        print key


print "Obj2 Attributes"
for j in range(0, len(obj2)):
    for key, value in obj2[i].items():
        print key