【问题标题】:How to convert Json to Python object?如何将 Json 转换为 Python 对象?
【发布时间】:2021-06-22 02:54:50
【问题描述】:

如何将复杂的Json格式转成python?我觉得将附加的复杂 json 转换为 python 对象有困难,我必须稍后根据数据库验证这些数据。

json:

{
   "namespace":"Data.Datapoint",
   "type":"record",
   "name":"Blood Donar",
   "fields":[
      {
         "name":"id",
         "type":"int"
      },
      {
         "name":"donor_number",
         "type":"string"
      },
      {
         "name":"birth_date",
         "type":{
            "type":"int",
            "logicalType":"date"
         },
         "doc":"Birth Date"
      },
      {
         "name":"height",
         "type":[
            "int",
            "null"
         ],
         "doc":"Height"
      },
      {
         "name":"applicant_ts",
         "type":[
            {
               "type":"long",
               "logicalType":"timestamp-millis"
            },
            "null"
         ],
         "doc":"Creation Timestamp"
      },
      {
         "name":"arm_preference_ind",
         "type":[
            "string",
            "null"
         ],
         "doc":"Arm Preference; Selection from list"
      },
      {
         "name":"abo_ind",
         "type":[
            "string",
            "null"
         ],
         "doc":"Blood Type/ABO"
      },
      {
         "name":"vein_grading_ind",
         "type":[
            "string",
            "null"
         ],
         "doc":"Vein Grade"
      }
   ]
}

【问题讨论】:

  • 你在使用json.loads吗?什么不工作?

标签: python json dictionary


【解决方案1】:
import json

data = '''
{ "namespace": "Data.Datapoint", "type": "record", "name": "Blood Donar", "fields": [ { "name": "id", "type": "int" }, { "name": "donor_number", "type": "string" }, { "name": "birth_date", "type": { "type": "int", "logicalType": "date" }, "doc": "Birth Date" }, { "name": "height", "type": [ "int", "null" ], "doc": "Height" }, { "name": "applicant_ts", "type": [ { "type": "long", "logicalType": "timestamp-millis" }, "null" ], "doc": "Creation Timestamp" }, { "name": "arm_preference_ind", "type": [ "string", "null" ], "doc": "Arm Preference; Selection from list" }, { "name": "abo_ind", "type": [ "string", "null" ], "doc": "Blood Type/ABO" }, { "name": "vein_grading_ind", "type": [ "string", "null" ], "doc": "Vein Grade" } ] }
'''

json_data = json.loads(data)

json_data 是你的python dict obj。

如果你想要来自网络的 json 数据,你可以试试这个

import json
import requests
response = requests.get("https://jsonplaceholder.typicode.com/todos")
todos = json.loads(response.text)

【讨论】:

  • 如果您从网络上取回 json,您可以执行 response.json() 如果您遇到错误,然后删除 ()
猜你喜欢
  • 2011-09-28
  • 1970-01-01
  • 2018-01-08
  • 1970-01-01
  • 2017-07-29
  • 2018-10-11
  • 2021-06-20
  • 2016-09-23
  • 2021-08-09
相关资源
最近更新 更多