Search code examples
type-conversionapache-nifijython

Converting a string that represents a list into an actual list in Jython?


I have a string in Jython that represents a list of JSON arrays:

[{"datetime": 1570216445000, "type": "test"},{"datetime": 1570216455000, "type": "test2"}]

If I try to iterate over this though, it just iterates over each character. How can I make it iterate over the actual list so I can get each JSON array out?

Background info - This script is being run in Apache NiFi, below is the code that the string originates from:

from org.apache.commons.io import IOUtils
...    
def process(self, inputStream):
        text = IOUtils.toString(inputStream,StandardCharsets.UTF_8)

Solution

  • You can parse a JSON similar to how you do it in Python.

    Sample Code:

    import json
    
    # Sample JSON text
    text =  '[{"datetime": 1570216445000, "type": "test"},{"datetime": 1570216455000, "type": "test2"}]'
    
    # Parse the JSON text
    obj = json.loads(text)
    
    # 'obj' is a dictionary
    print obj[0]['type']
    print obj[1]['type']
    

    Output:

    > jython json_string_to_object.py
    test
    test2