Import mapping: JSON with variable key

2
Hi Does anyone have quick solution for parsing JSON with variably key names without having to implement Java? For example:   { "feedback":{ "202de1e51639ae0":{ "request_duration":106175 } } } In the above example "202de1e51639ae0" is a key which varies, but the value does not. Evalling the relevant example JSON (available at https://docs.mendix.com/refguide/monitoring-mendix-runtime) at http://jsonpath.com/ some solutions come to mind, e.g. $.feedback.* Thanks
asked
2 answers
7

This is a common issue when working with JSON in Mendix.  So far my solution has been to change the json string to a format that can be parsed e.g.

{
  "feedback":{
    "code1":{
      "request_duration":106175
    },
    "code2":{
      "request_duration":106175
    }
  }
}

Should be converted to 

{
  "feedback":[
    {
      "key" : "code1",
      "request_duration":106175
    },
    {
      "key" : "code2",
      "request_duration":106175
    }
  ]
}

This can then be easily mapped. Depending on the JSON you can do the transformation with a string replace or in java by parsing the json and then restructuring it.

Hope this helps

 

EDIT:

Here is java code snippet to do the restructuring

JSONObject json = new JSONObject(json_string);
JSONObject feedback = json.getJSONObject("feedback");
JSONArray restructured_feedback = new JSONArray();
Iterator<String> iter = feedback.keys();
while ( iter.hasNext() ) {
	String key = iter.next();
	JSONObject o = feedback.getJSONObject(key);
	o.put("key", key);
	restructured_feedback.put(o);
}
json.put("feedback", restructured_feedback);

 

answered
0

I’ve published a Mendix module with a similar approach to transform the JSON into an array

https://marketplace.mendix.com/link/component/212893

 

answered