Reputation: 1
I have a JSON object that I want to add to an existing JSON Ojbect. When I add the object, it is added to bottom of the JSON, even though, the code added the new object first.
Here is an example of the JSON...
{
"Header": {
"ID": "Bob",
"Description": "Description header_dict"
},
"Body": {
"ItemInvolvesShortfall": {
"SpecifiedBy": {
"category": "Fibre To The Node",
"version": "1.2.0",
"type": "Shortfall Specification",
"ID": "FTTN Shortfall"
},
"DescribedBy": {
"Characteristic": {
"type": "Automatically fulfillable",
"ID": "pillar-patch"
},
"value": "Yes"
}
},
"ID": "Bob",
"Description": "Description body_dict"
}
}
This is what I want the JSON to look like. ID and Description should be before ItemInvolvesShortfall.
….
"Body": {
"ID": "Bob",
"Description": "Description body_dict",
"ItemInvolvesShortfall": {
"SpecifiedBy": {
"category": "Fibre To The Node",
"version": "1.2.0",
"type": "Shortfall Specification",
"ID": "FTTN Shortfall"
},
"DescribedBy": {
"Characteristic": {
"type": "Automatically fulfillable",
"ID": "pillar-patch"
},
"value": "Yes"
}
}
}
This is the code snippet.
#!/usr/bin/env python
import json
import objectpath
import collections
#READ JSON OFF DISK
data = json.loads(open("/Users/AAAAAAAAAA/Documents/Python/Tuples/json/FTTN.json").read())
json_tree = objectpath.Tree(data['ManageTicketOfWorkRequest'])
#LOOK FOR A JSON OBJECT - ItemInvolvesShortfall
result = tuple(json_tree.execute('$..ItemInvolvesShortfall'))
new_dict=collections.OrderedDict()
header_dict={}
body_dict=collections.OrderedDict()
# CREATE HEADER
header_dict["Header"]={
"ID":"Bob",
"Description":"Description header_dict" }
# CREATE BODY
body_dict={"Body":{
"ID":"Bob",
"Description":"Description body_dict" }
}
#ADD BODY INTO NEW DICTIONARY
new_dict.update(header_dict)
for i in result:
#ADD THE ITEMINVOLVESSHORTFALL INTO BODY. THE ID & DESCRIPTION
#WHICH IS FIRST, NOT BE PUSH BACK. SHOULD I USE A POP OR POP_LEFT
#OR USE A APPEND OR APPEND_LEFT
body_dict["Body"]["ItemInvolvesShortfall"]=i
print('INFO:04 ', a)
print(body_dict)
new_dict.update(body_dict)
print(" ", body_dict)
print("INFO05: ", body_dict)
new_dict.update(body_dict)
print("INFO06: ", new_dict)
Upvotes: 0
Views: 135
Reputation: 20424
Dictionaries in Python (and most other languages) have no order to them - they are a set (unordered collection) of key:value
pairs. Hence the argument that they are in the wrong order is incorrect as the premise that the data structure has an order is false.
Upvotes: 1