【问题标题】:how to parse json data content?如何解析json数据内容?
【发布时间】:2019-12-19 22:41:12
【问题描述】:

作为 python 新手,我想实现以下目标:
我的 json 输入如下所示:

{
"organisaties": [
    {
        "oin": "00000001855432950000",
        "naam": "ABG - organisatie",
        "status": "Actief",
        "kvkNummer": "63865718",
        "organisatieCode": null,
        "organisatieType": null,
        "afgifteDatum": "2016-05-22T22:00:00Z",
        "laatstAangepastDatum": "2018-05-07T22:00:00Z",
        "intrekDatum": null
    },
    {
        "oin": "00000004145716135000",
        "naam": "ActiecentrumVeiligheid en Zorg",
        "status": "Actief",
        "kvkNummer": null,
        "organisatieCode": null,
        "organisatieType": null,
        "afgifteDatum": "2019-09-16T09:45:49Z",
        "laatstAangepastDatum": "2019-09-19T09:46:14Z",
        "intrekDatum": null,
        "hoofdOIN": {
            "id": "https://portaal.digikoppeling.nl/registers/api/v1/organisaties/00000001825783434000"
        }
    },
    {
        "oin": "00000004000000140000",
        "naam": "Agentschap SZW",
        "status": "Ingetrokken",
        "kvkNummer": null,

。 .

我可以从文件中读取它,并且从互联网上我了解到可以将此 json 格式的文本加载到字典中。用下面的 sn -p

inputfile_object = open('organisaties_all.txt', 'r') x = inputfile_object.read() y = json.loads(x)

y 是一个带有一(1)个键“organisaties”的字典,y.values() 转储 1161 条记录的整个小节(在这种情况下,每条记录都以“oin”字段开头。

此外,我可以像这样打印单个记录的子内容

print (y["organisaties"][200]["oin"])

但是,我想遍历所有单个元素并提取其中的字段内容。 我目前看不到如何做到这一点

请就如何完成此方案提出建议,或者如果有更好的方法,请告诉我

谢谢

彼得

【问题讨论】:

    标签: python json loops dictionary parsing


    【解决方案1】:

    你可以这样迭代,IIUC:

    for items in f['organisaties']: 
        print(items['oin']) 
    

    【讨论】:

      【解决方案2】:

      我给你 2 个选项来解析你的 json 文件:

      import json
      with open('test1.json', 'rt') as f:
        data = json.load(f)
      
      # Option 1 with a loop
      for x in data['organisaties']:
          print(x['oin'])
      
      # Option 2 using pandas
      # pip install pandas (for install the library)
      import pandas as pd
      df = pd.DataFrame.from_dict(data['organisaties'])
      print(df['oin'])
      # With pandas is more easy to convert the information to to_csv
      df.to_csv('test1.csv',index=False)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-14
        • 1970-01-01
        • 2020-08-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多