I have a map of json path and its associated value. I want to create json using this path key and attach value at the end. Something like input as:
{key: "name1.name2.name3", value: "value1"},
{key:"name1.name2.name4", value: "value2"},
{key:"name1.name5[0]", value: "value3"},
{key:"name1.name5[1]", value: "value4"}
Output as:
{"name1":
{"name2":
{"name3":"value1",
"name4":"value2"
}
},
"name5":["value3","value4"]
}
There can be a list as well. Is there any library I can use?
CodePudding user response:
Well, long time ago in a company far away I used apache OGNL library that could do something like this. Here is the link: OGNL. But also, today most JSON parsing is done with Jackson or Gson libs. Also a quick search in google "apache jsonpath library" gave some nice links. See this one: JSONPath - Apache Camel
CodePudding user response:
Implemented the comment from @amant singh. https://github.com/wnameless/json-flattener
Maven dependency:
<dependency>
<groupId>com.github.wnameless.json</groupId>
<artifactId>json-flattener</artifactId>
<version>0.13.0</version>
</dependency>
Test:
Map<String,String> map = new HashMap<>();
map.put("name1.name2.name3", "value1");
map.put("name1.name2.name4", "value2");
map.put("name1.name5[0]", "value3");
map.put("name1.name5[1]", "value4");
System.out.println(map);
String unflatten = JsonUnflattener.unflatten(map);
System.out.println(unflatten);
Output:
{name1.name5[1]=value4, name1.name5[0]=value3, name1.name2.name3=value1, name1.name2.name4=value2}
{"name1":{"name5":["value3","value4"],"name2":{"name3":"value1","name4":"value2"}}}
