Had some problems with json strings

I'm using ignition to get the data via api and I get a string of json type.

import json
import urllib2
url="http://localhost:8080/EProduction/BinWeight"
formData={
	"part":"637724000A",
    "bldg":"ACP-105",
    "startTime":"2023-12-11 06:30:00",
    "stopTime":"2023-12-11 16:29:59"
}
jsonData = json.dumps(formData)
request = urllib2.Request(url, data=jsonData,headers={'Content-Type': 'application/json'})
response = urllib2.urlopen(request)
respData = response.read()
print respData
respData = system.util.jsonDecode(respData)
print "jsonDecode:",type(respData)
print "jsonDecode:",respData

result

{
"status":10000,
"msg":"SUCCESS",
"data":[
{
"lot":"12092 / 21",
"contQuantity":226.20000000000002
},
{
"lot":"12092 / 45",
"contQuantity":227.34999999999
},
{
"lot":"12094 / 246",
"contQuantity":226.5
},
{
"lot":"12094 / 6",
"contQuantity":224.15
},
{
"lot":"12097 / 245",
"contQuantity":227.05
},
{
"lot":"12097 / 60",
"contQuantity":220.1
}
]
}

jsonDecode: <type 'dict'>
jsonDecode: {u'msg': 'SUCCESS', u'data': [{u'contQuantity': 226.20000000000002, u'lot': '12092 / 21'}, {u'contQuantity': 227.34999999999, u'lot': '12092 / 45'}, {u'contQuantity': 226.5, u'lot': '12094 / 246'}, {u'contQuantity': 224.15, u'lot': '12094 / 6'}, {u'contQuantity': 227.05, u'lot': '12097 / 245'}, {u'contQuantity': 220.1, u'lot': '12097 / 60'}], u'status': 10000}

After system.util.jsonDecode() function conversion, dict type key-value pairs inside the change, it seems to be in accordance with the java HashList type sorting
This is not what I want.
I'd like the order of the converted structures to still be as returned by the api and that will help me to manage the data in a unified way.
How do I solve this problem?

Why does it matter what order they are in? Objects are accessed by key, and by definition a JSON object is unordered (and so are python dictionaries and Java HashMaps).

1 Like

You'd need to make your own json parser and use collections.OrderedDict. But don't do it. I really doubt you actually need to keep the order.

Indeed, but it makes JSON extremely unfriendly to source code control. There are places where SortedMap<String, Object> should be used instead, preferably with an alphanumeric comparator for the keys.

2 Likes

For display or troubleshooting, sometimes you do want the order preserved. An OrderedDict can make that easier. Then switch to dict for production.

Last time the OP was here, he was using 7.9, so my bet is that it will go to a dataset by the time it's all done.

YMMV, depending on the datset size, as OrderedDict is slower than dict.

def toOrderedDict(jsonIn):
	''' A helper function to convert a flat array of key-value pairs 
    	in JSON to an OrderedDict.
	'''
	import json
	from collections import OrderedDict
	
	return json.loads(jsonIn, object_pairs_hook=OrderedDict)
2 Likes