user3879701
user3879701

Reputation: 23

How to parse json string using jsonpath?

I need to parse the json in example1 using jsonpath similar to the below example2. But could not find the path since the type of the json is string. Please suggest me some possible ways to parse the json string to modify the value for colourCode dynamically.

Example1:

{
    "payload": "{\"carBrand\":{\"model\":{\"colourCode\":2147483647}}}"
}

Example2:

{phone:{phoneType:"iPhone","cat":"11"}}

Jsonpath:

$.phone.phoneType

This will return "iPhone"

Upvotes: 0

Views: 1795

Answers (1)

Ratish Bansal
Ratish Bansal

Reputation: 2462

You can achieve your goal with JsonPath library on its own. Here is an example:

String jsonString ="{\"phone\":{\"phoneType\":\"iPhone\",\"cat\":\"11\"}}";
String jsonExp = "$.phone.phoneType";
DocumentContext docCtx = JsonPath.parse(jsonString);
JsonPath jsonPath = JsonPath.compile(jsonExp);
String val1=docCtx.read(jsonPath);
System.out.println(val1); // print iPhone

Maven Dependency

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

You can refer to the documentation below for various other api's you can use.

https://github.com/json-path/JsonPath/blob/master/README.md
https://www.baeldung.com/guide-to-jayway-jsonpath

Upvotes: 1

Related Questions