Krwasch
Krwasch

Reputation: 49

convert Map with JSONPath to json string

I have a map like following:

"key1": "value1",
"list[0].key1": "listkeyvalue1"
"list[0].key2": "listkeyvalue2"
"list[1].key1": "listkeyvalue1"
"list[1].key2": "listkeyvalue3"

Is there a framework which converts this key-value pairs into an json object/string for me, regarding the [x] instead of just flat? When currently using something like Jackson ObjectMapper I just get the flat output I know of ways doing it on my own, just searching for a more elegant way

new ObjectMapper().writeValueAsString(map);

leads to JSON String

{
"key1": "value1",
"list[0].key1": "listkeyvalue1"
"list[0].key2": "listkeyvalue2"
"list[1].key1": "listkeyvalue1"
"list[1].key2": "listkeyvalue3"
}

but I want the output to be:

{
    "key1": "value1",
    "list": [
        {
            "key1": "listkeyvalue1",
            "key2": "listkeyvalue2"
        },
        {
            "key1": "listkeyvalue1",
            "key2": "listkeyvalue3"        
        }
    ]
}

Upvotes: 0

Views: 648

Answers (2)

Pao
Pao

Reputation: 843

Among Jackson's configuration options is pretty-printing: https://github.com/FasterXML/jackson-databind#user-content-10-minute-tutorial-configuration

Upvotes: 0

Raymond Choi
Raymond Choi

Reputation: 1271

Library Josson function unflatten() with parameter '.[]' as the delimiter characters.

https://github.com/octomix/josson

Josson josson = Josson.fromJsonString(
    "{\"key1\": \"value1\"," +
    "\"list[0].key1\": \"listkeyvalue1\"," +
    "\"list[0].key2\": \"listkeyvalue2\"," +
    "\"list[1].key1\": \"listkeyvalue1\"," +
    "\"list[1].key2\": \"listkeyvalue3\"}");
JsonNode node = josson.getNode("unflatten('.[]')");
System.out.println(node.toPrettyString());

Output

{
  "key1" : "value1",
  "list" : [ {
    "key1" : "listkeyvalue1",
    "key2" : "listkeyvalue2"
  }, {
    "key1" : "listkeyvalue1",
    "key2" : "listkeyvalue3"
  } ]
}

Upvotes: 1

Related Questions