gpt4 book ai didi

python - 如何使用python在JSON数据中添加方括号

转载 作者:太空宇宙 更新时间:2023-11-04 08:44:27 24 4
gpt4 key购买 nike

所以我有如下所示的 json 数据:

"responses":[
{
"ResponseID" : "R_1mhpDCQzIOlVfPT",
"ResponseSet" : "Default Response Set",
"IPAddress" : "",
"StartDate" : "2016-08-04 11:52:36",
"EndDate" : "2016-08-04 11:52:53",
"RecipientLastName" : "",
"RecipientFirstName" : "",
"RecipientEmail" : "",
"ExternalDataReference" : "",
"Finished" : "1",
"Status" : "1",
"Q5" : "",
"Q6" : "",
"Q7" : "",
"Q8" : "",
"Q9" : "",
"Q10" : "",
"Q11" : "",
"Q12" : "",
"LocationLatitude" : "33.414794921875",
"LocationLongitude" : "-111.90930175781",
"LocationAccuracy" : "-1"
},

我基本上想获取所有 Q,并将它们放入 json 中的 Questions 数组中。输出应如下所示:

"responses":[
{
"ResponseID" : "R_1mhpDCQzIOlVfPT",
"ResponseSet" : "Default Response Set",
"IPAddress" : "",
"StartDate" : "2016-08-04 11:52:36",
"EndDate" : "2016-08-04 11:52:53",
"RecipientLastName" : "",
"RecipientFirstName" : "",
"RecipientEmail" : "",
"ExternalDataReference" : "",
"Finished" : "1",
"Status" : "1",
"Questions" : [
"Q5" : "",
"Q6" : "",
"Q7" : "",
"Q8" : "",
"Q9" : "",
"Q10" : "",
"Q11" : "",
"Q12" : ""
],
"LocationLatitude" : "33.414794921875",
"LocationLongitude" : "-111.90930175781",
"LocationAccuracy" : "-1"
}

我怎样才能解决这个问题并将其应用于 100 多个回复。这是我到目前为止所拥有的:

for filename in os.listdir('C:/Users/john/Desktop/Q/QD'):
if filename.endswith(".json") :
print(filename)
with open(filename, encoding="utf8") as data_file:
data = json.load(data_file)
for i in data['responses']:
for j in i:
if j.startswith('Q'):
print(j)
input("Press enter to continue...")

所有这些代码所做的就是加载数据并基本上遍历文件夹中的每个文件并将所有问题打印到控制台中。我将如何去追加问题字段并添加方括号?

最佳答案

这是一个工作示例:

for filename in os.listdir('C:/Users/john/Desktop/Q/QD'):
if filename.endswith(".json"):
with open(filename, encoding="utf8") as data_file:
data = json.loads(data_file)
for response in data['responses']:
questions = {}
for key in list(response.keys()):
if key.startswith('Q'):
questions[key] = response[key]
del response[key]

response['Questions'] = questions
print(response)

一些注意事项:

  1. 我正在使用 python3
  2. 我正在使用 list(response.keys()) 来生成 key 的副本,如果没有,del 稍后会在您更改字典时出错迭代时。
  3. 魔术只是将您的问题保存在临时 questions 字典中,并在稍后出现在响应中。
  4. 只是一个意见,你比我更了解输入,但是 startswith 可能会导致你在键以“Q”开头(如“quantity”等)时出现问题

关于python - 如何使用python在JSON数据中添加方括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41988698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com