Script JSON Format

I tried to output JSON data from Script Console. I see on output window order of JSON object is not correct. If I change key name output order change again. I attached pictures for



reference

Ignition uses Jython based on Python 2.7. This version of Python does not preserve dictionary order.

Try using a jython OrderedDict instead of a regular jython dictionary.

Consider also just not caring. Virtually every system that receives JSON is tolerant to keys in any order, because the spec doesn't say anything about the ordering of keys.

5 Likes

I do think IA should route all JSONification through instances of TreeMap with a human- and source-control-friendly case-sensitive alphanumeric comparator for the keys. Perhaps with an performance exception for payloads going straight to the browser.

Especially including system.util.jsonEncode(). So that all json that ends up on disk (including json from document or other tags) is deterministic.

The JSON spec may not care about key order, but lots of other dependent functionality does.

4 Likes

I also tried jsonEncode and OrderDict. It did not perform as expected.

Create your payload directly with OrderedDict, not in a regular dict.

import json
from collections import OrderedDict

payload=OrderedDict()
payload['Version'] = '1.0.0'
payload['Timestamp'] = 80
payload['CurrMachSpeed'] = OrderedDict(Test=30)

print json.dumps(payload)

Yielded this for me:

>>> 
{"Version": "1.0.0", "Timestamp": 80, "CurrMachSpeed": {"Test": 30}}
>>>

(Please learn to post code and results as code on this forum. Use the "preformatted text" button in the forum comment editor. Use screenshots only for context that cannot be conveyed otherwise.)

1 Like

May I ask the importance of being in a specific order? As Paul suggested, why care?

For browser and API traffic, it truly doesn't matter. Unordered (HashMaps) are fastest and should be used.

For human review, unordered keys are extremely hard for eyes to handle, unless there are only a few entries.

For source code control, unordered keys produce huge diffs for simple changes, and make merges extremely difficult.

Strictly speaking, they should also be made "pretty" with indentations and line breaks. The latter are especially important for source code control.

Thank you..