Ordered Dictionaries

Hi,

I would like create a json file in a specific format, however there are some restriction involved.

  1. Declared dictionaries not in my specific key order (d,c,a,b).
from collections import OrderedDict

mylist = []

myOrderedDict = OrderedDict()
myOrderedDict['d'] = 4
myOrderedDict['c'] = 3
myOrderedDict['a'] = 1
myOrderedDict['b'] = mylist

myOrderedDict #Intended result
dict(myOrderedDict) #dict changed my result

myDict = {}
myDict['d'] = 4
myDict['c'] = 3
myDict['a'] = 1
myDict['b'] = mylist

myDict #dict changed my result
  1. After assigning my dictionaries, I would like to encode the dictionaries then write to file.
    Below are two different method that I had tried but still unable to get the json string format that I required (d,c,a,b).
jsonStr = system.util.jsonEncode(dict(myOrderedDict),5)
print jsonStr

import json
jsonNewStr = json.dumps({	'd':4,
						'c':3,
						'a':1,
						'b':mylist},
			sort_keys=False,
			indent=4, separators=(',', ':'))
print jsonNewStr		

I have also checked that ignition running on python 2.7.
https://docs.inductiveautomation.com/display/DOC81/Python+Scripting

For python 3.7 onward dictionary will be in order according to source code (Reference from SO)

Is there a way to workaround or could I be doing it wrong?
Appreciate for any advise and thank you in advance.

I dont think transforming an ordered list to json will not preserve its order.
If order is that important you will have to add in keys from when they where entered tho i guess.

myOrderedDict = OrderedDict()
myOrderedDict[1] = {"d":4}
myOrderedDict[2] = {"c":3}
myOrderedDict[3] = {"a":1}
myOrderedDict[4] = {"b":[]}

myOrderedDict
jsonStr = system.util.jsonEncode(myOrderedDict)

Python’s builtin JSON library has a sort_keys parameter:
https://docs.python.org/2.7/library/json.html

That said, relying on explicit key ordering in JSON objects/Python dictionaries is almost certainly an antipattern.

2 Likes

dictionary

Yes, the sort_keys parameter is what I intended to use but I got an error previously by adding a cursive bracket to my OrderedDict in the json.dumps.

The code below is working for me now. Thanks!

from collections import OrderedDict

mylist = []

myOrderedDict = OrderedDict()
myOrderedDict['d'] = 4
myOrderedDict['c'] = 3
myOrderedDict['a'] = 1
myOrderedDict['b'] = mylist

import json
jsonNewStr = json.dumps(myOrderedDict,
			sort_keys=False,
			indent=4, separators=(',', ':'))

system.file.writeFile("D:\NewJson.json", jsonNewStr)
1 Like