引用列表中的某些值

时间:2014-02-06 04:53:24

标签: python json

我有以下json:

[
    {
        "name": "person 1",
        "phones": {
            "home": [
                "000-111-2222",
                "333-444-5555"
            ],
            "cell": "666-777-8888"
        }
    },
    {
        "phones": {
            "home": "123-456-7890"
        },
        "name": "person 2"
    }
]

如果我使用open加载文件,它会将文件保存为类型列表。从我看到的使用open with,任何json对象将加载为类型dict,但任何json数组将加载为类型列表。

def get_json():
    file_name = raw_input("Enter name of JSON File: ")
    with open(file_name) as json_file:
        json_data = json.load(json_file)
        return json_data

我正在试图找出如何访问文件的某些部分,例如在加载json之后如果我想打印该行:

"name": "person 1",

将json保存为“list1”并为list1中的第一个元素调用print(print(list1 [0])))打印:

{u'name': u'person 1',
 u'phones': {u'cell': u'666-777-8888',
             u'home': [u'000-111-2222', u'333-444-5555']}}

这是我期望看到的,因为它首先在这个数组中“重视”,但我如何抓住“名称”:行特异性?

2 个答案:

答案 0 :(得分:2)

list1[0]是一本字典。因此,您只需访问name的值,如:

>>> print list1[0]['name']
u'person 1'

类似于说:

>>> info = list1[0]
>>> print info['name']
u'person 1'

答案 1 :(得分:1)

如果您确定数据的布局类似于OrderedDict,并且您不知道第一个对象中的第一对是什么,那么您可以使用[{..},..]

import json
from collections import OrderedDict

def get_json():
    file_name = raw_input("Enter name of JSON File: ")
    with open(file_name) as json_file:
        json_data = json.load(json_file, object_pairs_hook=OrderedDict)
    return json_data

然后您可以通过以下方式访问第一个dict中的第一对:

>>> 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')

但是,如果您真的关心订单,则不应将数据存储为JSON对象,而是使用数组。

在python 2.7中添加了

OrderedDictobject_pairs_hook