How to search/find In JSON with java
Asked Answered
P

4

12

I have a below JSON string from the below i want to find/search criteria in JSON String.

  1. To find the Number of keys present.
  2. To get the values of given key(if we have array)
    {
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
     "expensive": 10
    }

I am looking a solution like Groovy GPath Syntax

  • store.book - size of this array.
  • store.book[*].category - how may times the key present in the array.
  • store.bicycle - if it found it has to return true value
Perishing answered 11/3, 2015 at 9:11 Comment(0)
I
19

You can also use the JsonPath project provided by REST Assured. This JsonPath project uses Groovy GPath expressions. In Maven you can depend on it like this:

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

Examples:

To get a list of all book categories:

List<String> categories = JsonPath.from(json).get("store.book.category");

Get the first book category:

String category = JsonPath.from(json).get("store.book[0].category");

Get the last book category:

String category = JsonPath.from(json).get("store.book[-1].category");

Get all books with price between 5 and 15:

List<Map> books = JsonPath.from(json).get("store.book.findAll { book -> book.price >= 5 && book.price <= 15 }");

GPath is very powerful and you can make use of higher order functions and all Groovy data structures in your path expressions.

Infante answered 16/3, 2015 at 18:39 Comment(2)
Is there any documentation for this? groovy.codehaus.org/GPath seems to exist no more.Demodena
There's some documentation on the REST Assured website. See here: github.com/jayway/rest-assured/wiki/…Infante
D
1

Firstly, add json-path dependency in pom

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

Create a utility in Base Class that can be reused :

 public static String getValueFromJsonPath(String apiResponse, String jsonPath) {
        return JsonPath.read(apiResponse, jsonPath);
    }

One example of using this method :

getValueFromJsonPath(apiResponse, "$.store.book[0].category");

NOTE : Create overloaded method with different return types depending upon the expected result (like List for fetching a list from json)

Dandify answered 17/7, 2020 at 20:22 Comment(0)
F
0

First of all you have to add dependency

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>

Then you can use this code:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

public class Main {

    public static int PRETTY_PRINT_INDENT_FACTOR = 4;
    public static String TEST_XML_STRING =
        "<Result><ResultParameters><ResultParameter><Key>TransEndDate</Key><Value>20170731</Value></ResultParameter><ResultParameter><Key>Failed Reason</Key><Value>Operator 03058361178\03058365278 has no permission to perform the Check Balance service.</Value></ResultParameter><ResultParameter><Key>TransEndTime</Key><Value>123611</Value></ResultParameter></ResultParameters><ResultCode>2000</ResultCode><ResultType>0</ResultType><OriginatorConversationID>S_X20130129210125</OriginatorConversationID><ResultDesc>Initiator authentication error.</ResultDesc><TransactionID>000749213589</TransactionID><ConversationID>AG_20170731_00004c28e51f1f822e9e</ConversationID></Result>";

    public static void main(String[] args) {
        try {
            JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
            String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
            System.out.println(jsonPrettyPrintString);


            System.out.println("Element="+xmlJSONObj.getJSONObject("Result").getInt("ResultCode"));

        } catch (JSONException je) {
            System.out.println(je.toString());
        }
    }
}

// in it i am searching an element which is present in a json object 
Felske answered 31/7, 2017 at 10:23 Comment(0)
C
0

we can write generic json utility but before that we should have org.json dependency should be exist in to maven pom.xml.

public class PrintJsonPath_Version02 {

public static void main(String[] args) throws IOException {
    String jsonStr = new String(Files.readAllBytes(Paths.get(TestData.ECOMMERCE_TEST_DATA)));

    JSONObject jsonObject = new JSONObject(jsonStr);
    Map<String, Object> map = new HashMap<>();

    printJsonPath("", jsonObject, map);
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        System.out.println(entry.getKey() + " = " + entry.getValue());
    }

}

private static void printJsonPath(String path, Object object, Map<String, Object> map) {
    Object value = "";

    if (object instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) object;
        for (String key : jsonObject.keySet()) {
            value = jsonObject.get(key);
            String newPath = path.isEmpty() ? key : path + "." + key;
            printJsonPath(newPath, value, map);
        }
    } else if (object instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) object;
        for (int i = 0; i < jsonArray.length(); i++) {
            value = jsonArray.get(i);
            String newPath = path + "[" + i + "]";
            printJsonPath(newPath, value, map);
        }
    } else {
        if (!path.isEmpty() && path.charAt(0) == '.') {
            path = path.substring(1);
        }

        map.put(path, object);
    }
}

}

Output will be like below

Left Side will be JsonPath = Right Side will value

orders[0].customer.billing_address.city = bangalore orders[1].items[0].product_id = P003

orders[1].customer.phone = 555-555-5678

Cassondracassoulet answered 25/2, 2023 at 20:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.