JSON from streamed data in Python

110 Views Asked by At

I am simply trying to keep the following input and resulting JSON string in order.

Here is the input string and code:

import json

testlist=[]
# we create a list as a tuple so the dictionary order stays correct
testlist=[({"header":{"stream":2,"function":3,"reply":True},"body": [({"format": "A", "value":"This is some text"})]})]

print 'py data string: '

print testlist

data_string = json.dumps(testlist)

print 'json string: '

print data_string

Here is the output string:

json string: 
[{"body": [{"format": "A", "value": "This is some text"}], "header": {"stream": 2, "function": 3, "reply": true}}]

I am trying to keep the order of the output the same as the input.

Any help would be great. I can't seem to figure this one point.

1

There are 1 best solutions below

2
ChE On BEST ANSWER

As Laurent wrote your question is not very clear, but I give it a try:

OrderedDict.update adds in the above case the entries of databody to the dictionary. What you seem to want to do is something like data['body'] = databody where databody is this list [{"format":"A","value":"This is a text\nthat I am sending\n to a file"},{"format":"U6","value":5},{"format":"Boolean","value":true}, "format":"F4", "value":8.10}] So build first this list end then add it to your dictionary plus what you wrote in your post is that the final variable to be parse into json is a list so do data_string = json.dumps([data])