python - refrencing certain values in a list -
i have following json:
[ { "name": "person 1", "phones": { "home": [ "000-111-2222", "333-444-5555" ], "cell": "666-777-8888" } }, { "phones": { "home": "123-456-7890" }, "name": "person 2" } ]
if load file using open, saves file type list. have seen using open with, json object load type dict json array load type list.
def get_json(): file_name = raw_input("enter name of json file: ") open(file_name) json_file: json_data = json.load(json_file) return json_data
i'm trying figure out how access parts of file, such after loading json if wanted print line:
"name": "person 1",
saving json "list1" , calling print first element in list1 (print(list1[0]))) prints:
{u'name': u'person 1', u'phones': {u'cell': u'666-777-8888', u'home': [u'000-111-2222', u'333-444-5555']}}
which expect seeing how thats first "value" in array, how grab "name": line specificity?
you can use ordereddict
in case sure data has layout [{..},..]
, don't know first pair in first object , matters.
import json collections import ordereddict def get_json(): file_name = raw_input("enter name of json file: ") open(file_name) json_file: json_data = json.load(json_file, object_pairs_hook=ordereddict) return json_data
then can access first pair in first dict in following way:
>>> data = get_json() ... >>> next(iter(data[0].items())) # python 2/python 3 ('name', 'person 1') >>> data[0].items()[0] # python 2 ('name', 'person 1') >>> list(data[0].items())[0] # python 2/python 3 ('name', 'person 1')
however, if care order should not store data json object , use arrays instead.
ordereddict
, object_pairs_hook
added in python 2.7.
Comments
Post a Comment