如何在同一条消息中多次循环使用不同类型的嵌套JSON对象 [英] How to loop different types of nested JSON objects multiple times in the same message

查看:92
本文介绍了如何在同一条消息中多次循环使用不同类型的嵌套JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python noob再次出现.我正在尝试创建一个python脚本来自动生成具有多个项目的JSON,但使用for循环记录多次以生成它们,JSON消息的结构和基数如下:

Python noob here, again. I'm trying to create a python script to auto-generate a JSON with multiple item but records multiple times using a for loop to generate them, the JSON message is structured and cardinality are as follows:

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

在遍历同一对象之前,我已经获得了一些非常好的帮助,但是对于一个记录,例如,仅是itemRelationships记录.但是,一旦我尝试创建包含多个项目(即5个)以及itemAttribute,itemLocation和itemRelationships的单个实例的一条消息,由于我不断收到关键错误,因此它不起作用.我试图定义与我想做的事情有关的keyError,但是不能将我做错的事情与其他地方的例子联系起来.

I've had some really good help before for looping through the same object but for one record for example just the itemRelationships record. However as soon as I try to create one message with many items (i.e. 5) and a single instance of an itemAttribute, itemLocation and itemRelationships it does not work as I keep getting a key error. I've tried to define what a keyError is in relation to what I am trying to do but cannot link what I am doing wrong to the examples else where.

这是我目前的代码:

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))

我尝试过也尝试了这段代码,这给了我更好的结果:

I have tried also tried this code which gives me better results:

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,最后是四个item记录,如下所示:

This actually gives me a result but gives me messageHeader, item, itemAttributeA, itemLocation, itemRelations, and then four items records at the end as follows:

{
    "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"
                            }]
                        }]
                    }
                ]
            }]
        }]
    }]
}

我一整天都在努力工作,以使其正常工作,但是远离代码,我哪里出错了,任何帮助将不胜感激

I've been at this for the best part of a whole day trying to get it to work, butchering away at code, where am I going wrong, any help would be greatly appreciated

推荐答案

您的关闭信息.我认为您缺少的部分是将dict添加到当前的dict中,并使用for循环进行缩进.

Your close. I think the part your are missing is adding the dict to your current dict and indentation with your for loop.

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))

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

This code can also be shortened considerably if your example is close to what you truly desire:

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可能会匹配.

Another note: If you want messageID to be truly unique than you should probably look into a UUID; otherwise you may have message ids that match.

import uuid
unique_id = str(uuid.uuid4())
print(unique_id)

这篇关于如何在同一条消息中多次循环使用不同类型的嵌套JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆