将主要属性添加到 python 中的 json 对象

add main attribute to json object in python

我想将主要属性添加到 json 个对象。请参阅下面的 python 代码、json 对象和预期结果。

data.json

    [{
       "Full Address": "data1",
       "p1": "1",
       "p2": "6"  
      },
      {
      "Full Address": "data2",
      "p1": "1",
      "p2": "6"
    }]

预期结果

    [{
    "fields": {
      "Full Address": "data1",
      "p1": "1",
      "p2": "6"
       }
     },
     {
   "fields": {
    "Full Address": "data2",
    "p1": "1",
    "p2": "6"
   }
   }]

代码

import json
with open("data.json", 'r') as json_file:
 json_decoded = json.load(json_file)
for x in json_decoded:
 x['fields'] = ''
 with open("output.json", 'w') as json_out_file:
 json.dump(json_decoded, json_out_file, indent=2, ensure_ascii=False)

使用此代码我可以在 json 个对象中添加元素,但我的预期结果不同。

我的代码输出是

   [
     {
      "Full Address": "data1",
      "p1": "1",
      "p2": "6",
      "fields": " "
     },
     {
    "Full Address": "data2",
    "p1": "1",
    "p2": "6",
    "fields": " "
    }
  ]

Picture

试试这个:

import json

d = [
    {
        "Full Address": "data1",
        "p1": "1",
        "p2": "6"
    },
    {
        "Full Address": "data2",
        "p1": "1",
        "p2": "6"
    },
]

print(json.dumps([{"fields": {**i}} for i in d], indent=2))

输出:

[
  {
    "fields": {
      "Full Address": "data1",
      "p1": "1",
      "p2": "6"
    }
  },
  {
    "fields": {
      "Full Address": "data2",
      "p1": "1",
      "p2": "6"
    }
  }
]