如何解析 nestead json 并使用 python 从 dict 值构造关系数据库列

How to parse nestead json and construct relational database columns from dict values using python

下面是我的示例 json。我正在尝试提取 json 的 "attributes" 部分并插入到关系数据库中。但我需要将 "name" 值构造为关系列并将 "value" 值插入 table。我是说 {"name":"ID","value":"528BE6D9FD"​​} "ID" 作为一列并在 "ID" 下插入 528BE6D9FD。我的 python 学习才刚刚开始,所以不确定如何从字典值构造列。

d = 'C:/adapters/sample1.json'
json_data = open(d).read()
json_file = json.loads(json_data)
for children in json_file["events"]:
    #print (children)
    for grandchildren in children["attributes"]:
        #print(grandchildren)
        for key, value in grandchildren.iteritems():
                #if key == 'name':
                    print value



{
   "events":[
      {
         "timestamp":"2010-11-20T11:08:00.978Z",
         "code":"Event",
         "namespace":null,
         "version":null,
         "attributes":[
            {
               "name":"ID",
               "value":"528BE6D9FD"
            },
            {
               "name":"Total",
               "value":67
            },
            {
               "name":"PostalCode",
               "value":"6064"
            },
            {
               "name":"Category",
               "value":"More"
            },
            {
               "name":"State",
               "value":"QL"
            },
            {
               "name":"orderDateTime",
               "value":"2010-07-20T12:08:13Z"
            },
            {
               "name":"CategoryID",
               "value":"1091"
            },
            {
               "name":"billingCountry",
               "value":"US"
            },
            {
               "name":"shipping",
               "value":"Go"
            },
            {
               "name":"orderFee",
               "value":77
            },
            {
               "name":"Name",
               "value":"Roy"
            }
         ]
      }
   ]
}

就提取 json 数据的 attributes 散列而言,我会这样做:

json_path = "c:\adapters\sample1.json"
with open(json_path) as json_file:
    json_dict = json.load(json_file)

attributes = json_dict['events'][0]['attributes']

现在,我不知道您使用的是哪个数据库系统,但无论如何,您都可以使用列表理解提取名称和值,如下所示:

names = [key['name'] for key in attributes]
values = [key['value'] for key in attributes]

如果需要,现在只需创建一个 table,将 names 作为列 headers 插入,并将 values 作为与 [=13= 相关的单行插入].