简体   繁体   中英

Nesting with JSON Library in Python

I'm struggling to get my Python Code to work to output the correct nesting and formatting for my JSON messages. My problem is I am unable to nest the objects in the JSON the way the sample JSON has been given, as this is only how the source system will accept it. I've read the documentation and other tutorials etc online but nothing I have found works for this problem.

Here is the sample JSON I have to work with and contains the right formatting:

    {"messageId": "ID,"messageType": "Type","createdDateTime": "2019-01-01T10:10:10Z","recordOne": [{"dataItemOne": "E123345","dataItemTwo": "2019-01-01T12:12:12Z","attributesRecord": {"attributesOne": 22,"attributesTwo": 24,},"recordTwo": {"dataItemOne": "L22","dataItemTwo": "EL","dataItemThree": "ADDFES334S",},"recordThree": [{"itemOne": "P44587"}]}]}

And here is my code

import datetime
import json

datetime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")

data = {'messageId': 'ID',
        'messageType': 'Type',
        'createdDateTime': datetime}

data1 = {'recordOne': []}

data1['recordOne'].append({
    'dataItemOne': 'E123345',
    'dataItemTwo': datetime,
})

datas = [data, data1]

with open('mata.json', 'w') as outfile:
    data = json.dumps(data)
    json.dump(datas, outfile)

This gives my this type of JSON:

    [{"messageId": "ID","messageType": "Type","createdDateTime": "2019-03-14T20:31:55Z"}, {"recordOne": [{"dataItemOne": "E123345","dataItemTwo": "2019-03-14T20:31:55Z"}]}]

My main issues are I am unable to output the file to:

  • Start with just a curly braces ie {"messageId": "ID" and not [{"messageId": "ID"
  • I cannot get recordOne to format as "recordOne": [{
  • Then output attributesRecord as under recordOne as "attributesRecord": {
  • Then Nest fields under attributeRecords
  • Records recordTwo & recordThree I cannot create anymore than one object

Can anyone help me please and please excuse me I'm a noob?

NB - To get round it I created a separate script that printed the correct nesting and formatting but I was given a hard time and told to use the library, I am aware there are limitations to the library and not sure of this is one of them.

Take a look at the piece of code below

import datetime
import json

dt = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")

data = {'messageId': 'ID',
        'messageType': 'Type',
        'createdDateTime': dt}

data['recordOne'] = [{
    'dataItemOne': 'E123345',
    'dataItemTwo': dt
}]

# since recordOne contains a list, we use [0] to paste stuff inside it
data['recordOne'][0]['attributesRecord'] = {
    'attributesOne': 22,
    'attributesTwo': 24
}

data['recordTwo'] = {
    ...
}

# and so on and so forth

with open('mata.json', 'w') as outfile:
    json.dump(data, outfile)

The main thing to take away from this is that if you want to add something to your dictionary, you can just create a new key by writing data['recordOne'] and data['recordOne'][0]['attributesRecord'] , and whilst doing that, you can also assign it values that you want.

If you want to keep nesting, then just keep adding to the levels of keys. Keep in mind that if you are putting the dictionaries inside lists, you will have to access the key-value pairs inside the list using their respective indexes (such as the [0] )

As some of your dictionaries must also be inside lists, so I would add them as such (see the first data['recordOne'] ).

And finally, json.dumps() is used to create strings, while json.dump() is used to write to a file. So use that. Hope this helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM