2

I have following JSON

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  },
  "phoneNumbers": [
    {
      "type"  : "iPhone",
      "number": "0123-4567-8888"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910"
    }
  ]
}

and $.phoneNumbers[:1].type json path to extract phone number type iPhone value but the output is

[
  "iPhone"
]

I would like to get it as simple string like iPhone. How do i create the JSON path to strip double quote " and [ ?

Nik
  • 204
  • 3
  • 20

2 Answers2

1

You cannot remove [ & " directly from JSON Path, However, you can use this replace function given here https://community.apigee.com/questions/63281/how-to-remove-square-bracket-and-double-quotes-fro.html

var extracted_json = ["vIMS"]; // use context.getVariable("<<extracted-variable>>");
modifiedJson = JSON.stringify(extracted_json).replace(/[\[\]"]+/g,"");
context.setVariable("final-variable", modifiedJson)
Ayyub Kolsawala
  • 809
  • 8
  • 15
1

By default, using JsonPath to process JSON means you will get the result as a JSONArray. So, you have to make one more step to get the desired result.

For example,

@Test
public void test() {

     String json = "{\n" +
             "  \"firstName\": \"John\",\n" +
             "  \"lastName\" : \"doe\",\n" +
             "  \"age\"      : 26,\n" +
             "  \"address\"  : {\n" +
             "    \"streetAddress\": \"naist street\",\n" +
             "    \"city\"         : \"Nara\",\n" +
             "    \"postalCode\"   : \"630-0192\"\n" +
             "  },\n" +
             "  \"phoneNumbers\": [\n" +
             "    {\n" +
             "      \"type\"  : \"iPhone\",\n" +
             "      \"number\": \"0123-4567-8888\"\n" +
             "    },\n" +
             "    {\n" +
             "      \"type\"  : \"home\",\n" +
             "      \"number\": \"0123-4567-8910\"\n" +
             "    }\n" +
             "  ]\n" +
             "}";

     net.minidev.json.JSONArray iPhone = JsonPath.parse(json).read("$.phoneNumbers[?(@.type=='iPhone')].type");

     System.out.println("Type : " + iPhone.get(0).toString());
}

, will eventually print Type : iPhone

phuzi
  • 12,078
  • 3
  • 26
  • 50
dZ.
  • 404
  • 1
  • 5
  • 9
  • Thanks for reply but i'm looking for a solution in jsonpath itself. There is method return in framework so i can't modify it only i have pass the jsonpath in BDD step to verify whether expected value available on json path or not e.g. `response should have value 'available' at "$.[?(@.id == '${pet_id}')].status"` – Nik Nov 13 '19 at 13:11
  • @Nik not sure whether you can do that directly, as far as I know you can't. I will look through it in more detail and let you know if I achieve anything. – dZ. Nov 13 '19 at 13:59