代码之家  ›  专栏  ›  技术社区  ›  michele

分析JSON文件中的值?

  •  1353
  • michele  · 技术社区  · 14 年前

    我在一个文件中有这个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 回复  |  直到 6 年前
        1
  •  1998
  •   Nils Werner    6 年前

    我想伊格纳西奥说的是你的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"]
    

    试一试,看看是否有意义。

        2
  •  298
  •   Community datashaman    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)
    

    注意,这只在Python2.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'
    
        3
  •  68
  •   hellow Adolfo Casari    6 年前

    Justin Peel's answer 是非常有用的,但是如果您使用的是python 3,那么应该这样做:

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

    注:使用 json.loads 而不是 json.load . 在Python 3中, JSON负载 获取字符串参数。 JSON 采用类似文件的对象参数。 data_file.read() 返回字符串对象。

        4
  •  54
  •   smbanaei    11 年前
    data = []
    with codecs.open('d:\output.txt','rU','utf-8') as f:
        for line in f:
           data.append(json.loads(line))
    
        5
  •  13
  •   codeforester    7 年前

    “ultra json”或简单的“ujson”可以处理 [] 在JSON文件输入中。如果您正在将JSON输入文件作为JSON元素列表读取到程序中,例如, [{[{}]}, {}, [], etc...] UJSON可以处理字典列表、列表字典的任意顺序。

    你可以在 Python package index 而API几乎与Python内置的 json 图书馆。

    如果加载更大的JSON文件,UJSON也更快。与提供的同一链接中的其他python json库相比,您可以看到性能详细信息。

        6
  •  8
  •   sushmit    6 年前

    如果您在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
    
        7
  •  7
  •   Ramapati Maurya    7 年前
       # 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
    
        8
  •  5
  •   Bibin Wilson    6 年前

    此分析中有两种类型。

    1. 从系统路径分析文件中的数据
    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

        9
  •  4
  •   muratgozel    6 年前

    作为python3用户 ,

    两者之间的区别 load loads 方法非常重要,尤其是当您从文件中读取JSON数据时。

    如文件所述:

    JSON.Load:

    反序列化fp(a.read()—支持文本文件或二进制文件 包含json文档的文件)到使用此 转换表。

    负载:

    加载:反序列化s(str、bytes或bytearray实例 包含JSON文档)到使用此转换的python对象 表。

    加载方法可以直接读取打开的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