cancel
Showing results for 
Search instead for 
Did you mean: 

Python Dictionary Conversion in Script Snap

jskrable
New Contributor III

Hello,

I am trying to run a python script in the script snap that mocks up some test data for unit testing pipelines. The script relies on python data types such as list and dictionary to iterate through the incoming JSON document and manipulate it.

However, the document coming in are of type java.util.LinkedHashMap. When trying to convert to a python dict using dict(in_doc), it doesn’t process the document into a dict correctly.

Initial googling returned a number of jython bug around this issue. Is there any workaround for this that I can implement?

You can see the script here: test-file-gen/snap-file-gen.py at master · jskrable/test-file-gen · GitHub

Thanks,
Jack

2 REPLIES 2

jaybodra
New Contributor III

Hi Jack,

the best work around to this use json.loads and json.dumps; json.loads(in_doc.get(‘str_json’)). use a mapper with JSON.stringify() to represent JSON as string and then you can use json.loads() in the script.

Henchway
Contributor

Have you ever found a good solution to this besides converting it to a string prior?

Generally, the proposed method by @jaybodra works, but it seems more like a short-term workaround.
Additionally, I’m unable to retain the sorting of the dumps after re-loading it, even when telling it to do so specifically. So this only leaves the option of entering a string and passing out a string and then using JSON.parse(), then it will actually be an ordered json … 😮

json_input = json.loads(inDoc.get('content'))
json_string = json.dumps(json_input, sort_keys=True)
json_output = json.loads(json_string, object_pairs_hook=OrderedDict)

Best regards
Thomas