Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在列表中重新引用某些值_Python_Json - Fatal编程技术网

Python 在列表中重新引用某些值

Python 在列表中重新引用某些值,python,json,Python,Json,我有以下json: [ { "name": "person 1", "phones": { "home": [ "000-111-2222", "333-444-5555" ], "cell": "666-777-8888" } }, { "phones": {

我有以下json:

[
    {
        "name": "person 1",
        "phones": {
            "home": [
                "000-111-2222",
                "333-444-5555"
            ],
            "cell": "666-777-8888"
        }
    },
    {
        "phones": {
            "home": "123-456-7890"
        },
        "name": "person 2"
    }
]
如果使用with open加载文件,它会将文件另存为类型列表。从我使用openwith看到的情况来看,任何json对象都将作为dict类型加载,而任何json数组都将作为list类型加载

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]))打印:


这就是我希望看到的,这是这个数组中的第一个“值”,但我如何获取“名称”:行特异性?

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

>>> print list1[0]['name']
u'person 1'
这类似于说:

>>> info = list1[0]
>>> print info['name']
u'person 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
然后您可以通过以下方式访问first 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对象,而应使用数组

Python2.7中添加了
orderedict
object\u pairs\u hook

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