1

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?

4
  • Look at gson or jackson. Commented Jan 17, 2022 at 9:58
  • 2
    github.com/wnameless/json-flattener ? Commented Jan 17, 2022 at 10:00
  • @tgdavies I am using jackson in my project but it doesn't provide any util for this. Not sure of gson but tried googling but couldn't find much for creating json. Commented Jan 17, 2022 at 10:39
  • @amantsingh this could work. Thanks. Commented Jan 17, 2022 at 10:39

2 Answers 2

3

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"}}}
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

If I am not wrong, OGNL and Apache camel is more for reading value from object/json and not actually for creating the json object.
Yes, I guess so. But what I would try to do in general, I would try convert your input data, into a Map<String, Value> and then convert it into Json using any Json lib such as Jackson or Gson. I thought that OGNL can help you convert your input into standard map

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.