I can build JSON from simple dictionary {} and List [], but when I try to build more complex structures. I get '\' embedded in the output JSON.
The structure I want:
{"name": "alpha",
"results": [{"entry1":
[
{"sub1": "one"},
{"sub2": "two"}
]
},
{"entry2":
[
{"sub1": "one"},
{"sub2": "two"}
]
}
]
}
This is what I get:
{'name': 'alpha',
'results': '[{"entry1": "[{\\\\"sub1\\": \\\\"one\\\\"}, {\\\\"sub2\\\\": '
'\\\\"two\\\\"}]"}, {"entry2": "[{\\\\"sub1\\\\": \\\\"one\\\\"},
{\\\\"sub2\\\\": '
'\\\\"two\\\\"}]"}]'}
Note the embedded \\. Every time the code goes through json.dumps another \ is appended.
Here's code that almost works, but doesn't:
import json
import pprint
testJSON = {}
testJSON["name"] = "alpha"
#build sub entry List
entry1List = []
entry2List = []
topList = []
a1 = {}
a2 = {}
a1["sub1"] = "one"
a2["sub2"] = "two"
entry1List.append(a1)
entry1List.append(a2)
entry2List.append(a1)
entry2List.append(a2)
# build sub entry JSON values for Top List
tmpDict1 = {}
tmpDict2 = {}
tmpDict1["entry1"] = json.dumps(entry1List)
tmpDict2["entry2"] = json.dumps(entry2List)
topList.append(tmpDict1)
topList.append(tmpDict2)
# Now lets' add the List with 2 sub List to the JSON
testJSON["results"] = json.dumps(topList)
pprint.pprint (testJSON)
json.dumps(data). JSON is not special data type, it is serialization method representing some data in form of a string.