How to Parse a Dynamic JSON Key in a Nested JSON Result

How to parse a dynamic JSON key in a Nested JSON result?

Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.

Roughly the code will look like:


// searchResult refers to the current element in the array "search_result" but whats searchResult?
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();

while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();

// get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);

// do something here with the value...
}

How to parse dynamic nested JSON in Java using JSONObject.keys()

I was taught not to debug recursions by my lecturer.
Fortunately, I understood your idea and implemented it.

Think simple - imagine you are a node in the JSON:

  • If you are a JSONObject:
    • If you have the key - return the value.
    • If one of your children has it (recursion) - return it, else return null
  • If you are a JSONArray, return if one of your elements has the value (recursion)
  • You are not a JSONObject and not a JSONArray, return null.

Now it's easy to implement:

private static Integer getValueFromKey2(Object object, String key) {
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;

if (jsonObject.has(key)) {
return jsonObject.getInt(key);
}

return jsonObject.keySet().stream()
.map(childKey -> getValueFromKey2(jsonObject.get(childKey), key))
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
} else if (object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;

return IntStream.range(0, jsonArray.length())
.mapToObj(jsonArray::get)
.map(o -> getValueFromKey2(o , key))
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
} else {
return null;
}
}

Output:

From main: 103

How to parse a nested json object in postman which has dynamic keys?

This is a very horrible and flaky way to 'test' the values from the response JSON in the question. This assumes that the environment vars that were set in the previous request were account_id = 104 and location_id = 3. This does a hardcoded check to see that the FirstName property in that object, equals 'Rita'.

pm.test('Get the values', () => {
var jsonData = pm.response.json()[pm.environment.get('account_id')][pm.environment.get('location_id')]
pm.expect(jsonData[0].FirstName).to.equal('Rita')
})

It's difficult to tell what you actually want to do with the data and this test isn't something that I would use but if you just wanted an insight into how you would parse the data based on some environment vars this is at least a starting point.

If more information is provided, I will update my answer to reflect this.

How To Capture Dynamic Keys In Nested Python Dictionary

Maybe I misunderstand your intent, but you could look at

keys = list(data['attributes'].keys())

If there's only one key or you only need the first one take key = keys[0] or directly

key, *_ = data['attributes'].keys()

If there are more keys and you need them all, just iterate over them.

How can I parse JSON in GoLang if nested content uses dynamic keys?

Try this instead, looks like you just have your structure set up incorrectly:

http://play.golang.org/p/VRKbv-GVQB

You need to parse the entire json string, which is an object that contains a single element named items. items then contains a map of string -> Person objects.

If you only want to extract name and age from each person, you do it by grabbing data.Items["bvu62fu6dq"].Name.

If you want dynamic keys inside the Person, you'll need to do map[string]interface{} instead of Person in order to capture the dynamic keys again. It would look something like:

type Data struct {
Items map[string]map[string]interface{} `json:"items"`
}
...
fmt.Printf("%v\n", data.Items["bvu62fu6dq"]["name"]
fmt.Printf("%v\n", data.Items["bvu62fu6dq"]["age"]
fmt.Printf("%v\n", data.Items["bvu62fu6dq"]["xyz"]


Related Topics



Leave a reply



Submit