0

I have a generator which is generating a completely json scripts with random keys and values(quickcheck.generator). I want to read this string and get the values of the keys. The problem is that each time, a new json string is creating with different sizes, and also there is no access to know about the key names or value names. I should read the string blindly and reach to each key. Is there any solution?

Here is an example: Imagine I have below json script which is created by a generator:

{
            "key1": "value2",
            "key3": 1234,
            "key2": {
                "key4": true,
                "key7": "value3",
                "key6": "value1",
                "key5": 234
            }
}

I have it as a string, but like an invisible string that I am going to traverse on it.

Now I want to read each key and its value and compare them with a string and then based on this comparison I am going to create another json script!

What I have seen for jackson and other libraries, they know the name of each key and value and they are using those name to reach whatever they want.

But the difficulty that I here is that each time this json string is going to be created randomly by a generator, so I have no idea about the key name or value name or even the size of each block or anything related to json string! so each time I have a new json string that I am going to have access to its key, value pairs.

Thank you in advance!

2 Answers2

0

Since you don't know the keys, you could parse your JSON where you know it, i.e. at colons and commas. First split it at commas and you'll get an array of key/value strings, then split each at colons and you'll get a 2D array of this type:

[
    [key,value],
    [key,value]
]

In Java, you could have something like

public String[][] parseJSON(String JSONString){
    String[][] output = new String[JSONString.split(",").length][];
    int i = 0;
    for (String keyValuePair:JSONString.split(",")) {
        output[i++] = keyValuePair.split(",");
    }
    return output;
}
0

Using org.json, you can traverse the JSON like the following:

JSONObject jsonObject = new JSONObject(jsonStr);
jsonObject.keySet().forEach(key -> System.out.println(jsonObject.get(key)));

If you are interested nested keys, you can check if the value is a JSONObject.

Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12