Reputation: 649
I want to determine each attribut in a JSON format where i have no idea about the content of the JSON file.
For example i have these different files contenent:
[
{
"name": "abc",
"hobby": "swimming"
},
{
"name": "xyz",
"hobby": "programming"
}
]
and the second example:
[
{
"street": "PL EDOUARD BOUILLIERE",
"nb_places_totales": 249
},
{
"street": "CHE DU VERDON",
"nb_places_totales": 212
}
]
How can i parse and determine the attribut name using python?
Upvotes: 2
Views: 14938
Reputation: 1
This is how you get the attribute name. If you want values, print value instead of key.
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
Upvotes: -2
Reputation: 1335
You need to check for dictionary keys, in 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))
but every solution will be somehow content dependent anyway.
Upvotes: 0
Reputation: 4199
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()
this will result in:
[u'hobby', u'name']
[u'hobby', u'name']
Upvotes: 1
Reputation: 3081
Use the json package to parse the file. Then you can look at the keys of the first item in the data structure.
import json
with open(filename) as fid:
data = json.load(fid)
print(data[0].keys())
Upvotes: 3