I have a JSON string object, and I have to extract a value, but either I can split the JSON or I need to extract that value. Below is my JSON string.
[
{
"Code": "1",
"Name": "someName",
"rateCode": "1234",
"soldQty": 1,
"revAmnt": 120,
"pacPick": {
"pickDate": "2025-06-12",
"soldQty": 1
},
"invTyp": [
{
"inventoryTypeCode": "ASDF",
"soldQty": 1,
"revAmnt": 120
}
]
},
{
"Code": "1",
"Name": "someName",
"rateCode": "2345",
"soldQty": 1,
"revAmnt": 99.6,
"pacPick": {
"pickDate": "2025-06-12",
"soldQty": 1
},
"invTyp": [
{
"inventoryTypeCode": "ZXCV",
"soldQty": 1,
"revAmnt": 99.6
}
]
},
{
"Code": "1",
"Name": "someName",
"rateCode": "5678",
"soldQty": 1,
"revAmnt": 90,
"pacPick": {
"pickDate": "2025-06-12",
"soldQty": 1
},
"invTyp": [
{
"inventoryTypeCode": "POIU",
"soldQty": 1,
"revAmnt": 90
}
]
}
]
I need to extract only the soldQty
which is coming after the rateCode
. I tried
String sldQtyString = JsonPath.read(DataSet, "$..soldQty").toString();
And
String sldQtyString = JsonPath.read(DataSet, "$..soldQty\[0\]").toString();
But I am not able to get what I need.
Either I need to split each node into two
{
"Code": "1",
"Name": "someName",
"rateCode": "1234",
"soldQty": 1,
"revAmnt": 120,
"pacPick": {
"pickDate": "2025-06-12",
"soldQty": 1
},
and
"invTyp": [
{
"inventoryTypeCode": "ASDF",
"soldQty": 1,
"revAmnt": 120
}
]
And then I can fetch the required value.
Both solutions would be helpful.
It seems like you need to only top level object properties.
Just use a $.*.soldQty
path.
Explanation: $.*
selects all objects in the array (3 of them), then $.*
selects soldQty on that objects.
class JsonPathTest {
private static final String JSON = "...";
@Test
void shouldReturnOnlyTopLevelQuantities() {
JSONArray test = JsonPath.parse(JSON).read(JsonPath.compile("$.*.soldQty"));
assertThat(test).hasToString("[1,1,1]");
}
Tested on com.jayway.jsonpath:json-path:2.9.0
.