首页 文章

从JSON文件解析值?

提问于
浏览
1256

我在文件中有这个JSON:

{
    "maps": [
        {
            "id": "blabla",
            "iscategorical": "0"
        },
        {
            "id": "blabla",
            "iscategorical": "0"
        }
    ],
    "masks": [
        "id": "valore"
    ],
    "om_points": "value",
    "parameters": [
        "id": "valore"
    ]
}

我写了这个打印所有json文本的脚本:

json_data=open(file_directory).read()

data = json.loads(json_data)
pprint(data)

如何解析文件并提取单个值?

9 回答

  • 291

    我想Ignacio所说的是你的JSON文件不正确 . 当你应该有 {} 时,你有 [] . [] 用于列表, {} 用于词典 .

    以下是您的JSON文件的外观,您的JSON文件甚至不会为我加载:

    {
        "maps": [
            {
                "id": "blabla",
                "iscategorical": "0"
            },
            {
                "id": "blabla",
                "iscategorical": "0"
            }
        ],
        "masks": {
            "id": "valore"
        },
        "om_points": "value",
        "parameters": {
            "id": "valore"
        }
    }
    

    然后你可以使用你的代码:

    import json
    from pprint import pprint
    
    with open('data.json') as f:
        data = json.load(f)
    
    pprint(data)
    

    使用数据,您现在还可以找到如下值:

    data["maps"][0]["id"]
    data["masks"]["id"]
    data["om_points"]
    

    尝试一下,看看它是否有意义 .

  • 63

    如果您在python 3中,那么您将如何做到这一点

    {
      "connection1": {
        "DSN": "con1",
        "UID": "abc",
        "PWD": "1234",
        "connection_string_python":"test1"
      }
      ,
      "connection2": {
        "DSN": "con2",
        "UID": "def",
        "PWD": "1234"
      }
    }
    

    代码应该看起来像假设connection.json文件如上所示

    connection_file = open('connection.json', 'r')
    conn_string = json.load(connection_file)
    conn_string['connection1']['connection_string_python'])
    connection_file.close()
    >>>test1
    
  • 51

    "Ultra JSON"或只是"ujson"可以处理您的JSON文件输入中的 [] . 如果您正在将JSON输入文件作为JSON元素列表读入程序中;例如, [{[{}]}, {}, [], etc...] ujson可以处理任何字典列表,列表字典的任意顺序 .

    您可以在Python package index中找到ujson,并且API几乎与Python的内置 json 库相同 .

    如果你加载更大的JSON文件,ujson也会快得多 . 与提供的同一链接中的其他Python JSON库相比,您可以查看性能详细信息 .

  • 2

    此解析有两种类型 .

    • 从系统路径中解析文件中的数据

    • 从远程URL解析JSON .

    从文件中,您可以使用以下内容

    import json
    json = json.loads(open('/path/to/file.json').read())
    value = json['key']
    print json['value']
    

    这个arcticle解释了使用两个场景的完整解析和获取值 . Parsing JSON using Python

  • 8

    As a python3 user

    loadloads 方法之间的区别非常重要,尤其是当您从文件中读取json数据时 .

    如文档中所述:

    json.load:

    使用此转换表将fp(.read() - 支持包含JSON文档的文本文件或二进制文件)反序列化为Python对象 .

    json.loads:

    json.loads:使用此转换表将s(包含JSON文档的str,bytes或bytearray实例)反序列化为Python对象 .

    json.load方法可以直接读取打开的json文件,因为它能够读取二进制文件 .

    with open('./recipes.json') as data:
      all_recipes = json.load(data)
    

    因此,您的json数据可以按照此转换表指定的格式获得:

    https://docs.python.org/3.7/library/json.html#json-to-py-table

  • 7

    你的 data.json 应该是这样的:

    {
     "maps":[
             {"id":"blabla","iscategorical":"0"},
             {"id":"blabla","iscategorical":"0"}
            ],
    "masks":
             {"id":"valore"},
    "om_points":"value",
    "parameters":
             {"id":"valore"}
    }
    

    你的代码应该是:

    import json
    from pprint import pprint
    
    with open('data.json') as data_file:    
        data = json.load(data_file)
    pprint(data)
    

    请注意,这仅适用于Python 2.6及更高版本,因为它取决于with-statement . 在Python 2.5中使用 from __future__ import with_statement ,在Python <= 2.4中,请参阅Justin Peel's answer,这个答案是基于的 .

    您现在还可以访问单个值,如下所示:

    data["maps"][0]["id"]  # will return 'blabla'
    data["masks"]["id"]    # will return 'valore'
    data["om_points"]      # will return 'value'
    
  • 1854

    Justin Peel's answer真的很有用,但是如果你使用Python 3阅读JSON应该这样做:

    with open('data.json', encoding='utf-8') as data_file:
        data = json.loads(data_file.read())
    

    注意:使用 json.loads 而不是 json.load . 在Python 3中, json.loads 采用字符串参数 . json.load 采用类似文件的对象参数 . data_file.read() 返回一个字符串对象 .

  • 13
    data = []
    with codecs.open('d:\output.txt','rU','utf-8') as f:
        for line in f:
           data.append(json.loads(line))
    
  • 0
    # Here you go with modified json file:
       # data.json file : 
        {
            "maps": [
                {
                    "id": "blabla",
                    "iscategorical": "0"
                },
                {
                    "id": "blabla",
                    "iscategorical": "0"
                }
            ],
            "masks": [{
                "id": "valore"
            }],
            "om_points": "value",
            "parameters": [{
                "id": "valore"
            }]
        }
    
    
       # You can call or print data on console by using below lines
    
        import json
        from pprint import pprint
        with open('data.json') as data_file:
            data_item = json.load(data_file)
        pprint(data_item)
    
        print(data_item['parameters'][0]['id'])
    
        #Output : 
        #pprint(data_item) output as :
    
        {'maps': [{'id': 'blabla', 'iscategorical': '0'},
                  {'id': 'blabla', 'iscategorical': '0'}],
         'masks': [{'id': 'valore'}],
         'om_points': 'value',
         'parameters': [{'id': 'valore'}]}
        #print(data_item['parameters'][0]['id']) output as :
        valore
    

相关问题