gpt4 book ai didi

json - 如何在同一条消息中多次循环不同类型的嵌套 JSON 对象

转载 作者:行者123 更新时间:2023-12-04 21:30:00 25 4
gpt4 key购买 nike

再来一次 Python 菜鸟。我正在尝试创建一个 python 脚本来自动生成一个包含多个项目的 JSON,但使用 for 循环多次记录来生成它们,JSON 消息是结构化的,基数如下:

messageHeader[1]
-item [1-*]
--itemAttributesA [0-1]
--itemAttributesB [0-1]
--itemAttributesC [0-1]
--itemLocaton [1]
--itemRelationships [0-1]

在循环遍历同一个对象之前,我得到了一些非常好的帮助,但是对于一个记录,例如只有 itemRelationships 记录。但是,一旦我尝试创建包含多个项目(即 5 个)和 itemAttribute、itemLocation 和 itemRelationships 的单个实例的一条消息,它就不起作用,因为我不断收到关键错误。我试图定义与我正在尝试做的事情相关的 keyError 是什么,但无法将我做错的事情与其他地方的示例联系起来。

这是我的代码:
import json
import random

data = {'messageID': random.randint(0, 2147483647), 'messageType': 'messageType'}
data['item'] = list()

itemAttributeType = input("Please selct what type of Attribute item has, either 'A', 'B' or 'C' :")

for x in range(0, 5):
data['item'].append({
'itemId': "I",
'itemType': "T"})

if itemAttributeType == "A":
data['item'][0]['itemAttributesA']

data['item'][0]['itemAttributesA'].append({
'attributeA': "ITA"})

elif itemAttributeType == "B":
data['item'][0]['itemAttributesB']

data['item'][0]['itemAttributesB'].append({
'attributeC': "ITB"})

else:
data['item'][0]['itemAttributesC']

data['item'][0]['itemAttributesC'].append({
'attributeC': "ITC"})
pass

data['item'][0]['itemLocation'] = {
'itemDetail': "ITC"}

itemRelation = input("Does the item have a relation: ")
if itemRelation > '':
data['item'][0]['itemRelations'] = {
'itemDetail': "relation"}
else:
pass

print(json.dumps(data, indent=4))

我试过也试过这个代码,它给了我更好的结果:
import json
import random

data = {'messageID': random.randint(0, 2147483647), 'messageType': 'messageType'}
data['item'] = list()

itemAttributeType = input("Please selct what type of Attribute item has, either 'A', 'B' or 'C' :")

for x in range(0, 5):
data['item'].append({
'itemId': "I",
'itemType': "T"})

if itemAttributeType == "A":
data['item'][0]['itemAttributesA'] = {
'attributeA': "ITA"}

elif itemAttributeType == "B":
data['item'][0]['itemAttributesB'] = {
'attributeB': "ITB"}

else:
data['item'][0]['itemAttributesC'] = {
'attributeC': "ITC"}
pass

data['item'][0]['itemLocation'] = {
'itemDetail': "ITC"}

itemRelation = input("Does the item have a relation: ")
if itemRelation > '':
data['item'][0]['itemRelations'] = {
'itemDetail': "relation"}
else:
pass

print(json.dumps(data, indent=4))

这实际上给了我一个结果,但给了我 messageHeader、item、itemAttributeA、itemLocation、itemRelations,然后是最后的四个项目记录,如下所示:
{
"messageID": 1926708779,
"messageType": "messageType",
"item": [
{
"itemId": "I",
"itemType": "T",
"itemAttributesA": {
"itemLocationType": "ITA"
},
"itemLocation": {
"itemDetail": "location"
},
"itemRelations": {
"itemDetail": "relation"
}
},
{
"itemId": "I",
"itemType": "T"
},
{
"itemId": "I",
"itemType": "T"
},
{
"itemId": "I",
"itemType": "T"
},
{
"itemId": "I",
"itemType": "T"
}
]
}

我想要实现的是这个输出:
{
"messageID": 2018369867,
"messageType": "messageType",
"item": [{
"itemId": "I",
"itemType": "T",
"itemAttributesA": {
"attributeA": "ITA"
},
"itemLocation": {
"itemDetail": "Location"
},
"itemRelation": [{
"itemDetail": "D"
}]
}, {
"item": [{
"itemId": "I",
"itemType": "T",
"itemAttributesB": {
"attributeA": "ITB"
},
"itemLocation": {
"itemDetail": "Location"
},
"itemRelation": [{
"itemDetail": "D"
}]
}, {
"item": [{
"itemId": "I",
"itemType": "T",
"itemAttributesC": {
"attributeA": "ITC"
},
"itemLocation": {
"itemDetail": "Location"
},
"itemRelation": [{
"itemDetail": "D"
}]
}, {
"item": [{
"itemId": "I",
"itemType": "T",
"itemAttributesA": {
"attributeA": "ITA"
},
"itemLocation": {
"itemDetail": "Location"
},
"itemRelation": [{
"itemDetail": "D"
}]
},
{
"item": [{
"itemId": "I",
"itemType": "T",
"itemAttributesB": {
"attributeA": "ITB"
},
"itemLocation": {
"itemDetail": "Location"
},
"itemRelation": [{
"itemDetail": "D"
}]
}]
}
]
}]
}]
}]
}

我一整天都在做这件事,试图让它工作,在代码上大肆挥霍,我哪里出错了,任何帮助将不胜感激

最佳答案

你的接近。我认为您缺少的部分是添加 dict到您当前的 dict并用您的 for 缩进环形。

import json
import random

data = {'messageID': random.randint(0, 2147483647), 'messageType': 'messageType'}
data['item'] = list()

itemAttributeType = input("Please selct what type of Attribute item has, either 'A', 'B' or 'C' :")

for x in range(0, 5):
data['item'].append({
'itemId': "I",
'itemType': "T"})

if itemAttributeType == "A":
# First you need to add `itemAttributesA` to your dict:
data['item'][x]['itemAttributesA'] = dict()
# You could also do data['item'][x] = {'itemAttributesA': = dict()}

data['item'][x]['itemAttributesA']['attributeA'] = "ITA"
elif itemAttributeType == "B":
data['item'][x]['itemAttributesB'] = dict()

data['item'][x]['itemAttributesB']['attributeC'] = "ITB"

else:
data['item'][x]['itemAttributesC'] = dict()
data['item'][x]['itemAttributesC']['attributeC'] = "ITC"

data['item'][x]['itemLocation'] = {'itemDetail': "ITC"}

itemRelation = input("Does the item have a relation: ")
if itemRelation > '':
data['item'][x]['itemRelations'] = {'itemDetail': "relation"}
else:
pass

print(json.dumps(data, indent=4))

如果您的示例接近您真正想要的,此代码也可以大大缩短:
import json
import random

data = {'messageID': random.randint(0, 2147483647), 'messageType': 'messageType'}
data['item'] = list()

itemAttributeType = input("Please selct what type of Attribute item has, either 'A', 'B' or 'C' :")

for x in range(0, 5):
new_item = {
'itemId': "I",
'itemType': "T",
'itemAttributes' + str(itemAttributeType): {
'attribute' + str(itemAttributeType): "IT" + str(itemAttributeType)
},
'itemLocation': {'itemDetail': "ITC"}
}

itemRelation = input("Does the item have a relation: ")
if itemRelation > '':
new_item['itemRelations'] = {'itemDetail': itemRelation}
data['item'].append(new_item)

print(json.dumps(data, indent=4))

另注:如果你想要 messageID要真正独特而不是您应该查看 UUID ;否则您可能有匹配的消息 ID。
import uuid
unique_id = str(uuid.uuid4())
print(unique_id)

关于json - 如何在同一条消息中多次循环不同类型的嵌套 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55681612/

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