Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a subset of JSON properties and values using JSONPath

Given a JSON like:

{
  "a":1,
  "b":2,
  "c":3,
  "d":4,
  "e":5
}

How can I select out b, d and e to get the following JSON?

{
  "b":2,
  "d":4,
  "e":5
}

I want a JSON object and NOT only 2, 4 and 5 values?

This is what I'm trying with and failing:

$.[b,d,e]
like image 236
user3139545 Avatar asked Feb 05 '23 22:02

user3139545


2 Answers

JSONPath is not suitable for what you are trying to achieve: JSONPath is designed to select values and not key-value pairs. What you want could be achieved with Jackson or any JSON parser for Java.

If you want to go for Jackson here's the code that will do the trick:

String json = "{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}";

ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(json);

ObjectNode node = mapper.createObjectNode();
node.set("b", tree.get("b"));
node.set("d", tree.get("d"));
node.set("e", tree.get("e"));

String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);
like image 160
cassiomolin Avatar answered Feb 08 '23 14:02

cassiomolin


Elements must be in single quotes.

$.['b','d','e']

Works fine for JsonPath from com.jayway.jsonpath:json-path:2.4.0

like image 29
Javanshir Yolchiyev Avatar answered Feb 08 '23 14:02

Javanshir Yolchiyev