Search code examples
javascriptjsonjsonpath

Parse value from json object with json path


Given example

{
    "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"
        }
    ]
}

From $.phoneNumbers[0].type I can parse ["iPhone"] But I only wants iPhone as in string value. And if I try $.phoneNumbers[0].type[0] it returns i. And if I use the result in js like result[0] it returns [. At this point I do not know what to do, any help is welcome. I'm really new at this.


Solution

  • You are doing it right, except that you should use [0] not [:1]

    JSONpath, for some reason, always outputs an object or array on the screen display.

    When you actually use this syntax in Javascript, you will get a plain string, "iPhone", not an array ["iPhone"].

    Here is a comparison of what you get:

    JSONPath

    enter image description here

    Doing it in real Javascript

    const $ = {
        "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"
            }
        ]
    }
    console.log($.phoneNumbers[0].type)