Mammt
Mammt

Reputation: 67

Filtering list of string with Json Path

I have the following json example

{
    "address_components": [
        {
            "long_name": "43a",
            "short_name": "43a",
            "types": [
                "street_number"
            ]
        },
        {
            "long_name": "South Audley Street",
            "short_name": "S Audley St",
            "types": [
                "route"
            ]
        },
        {
            "long_name": "London",
            "short_name": "London",
            "types": [
                "postal_town"
            ]
        },
        {
            "long_name": "Greater London",
            "short_name": "Greater London",
            "types": [
                "administrative_area_level_2",
                "political"
            ]
        },
        {
            "long_name": "England",
            "short_name": "England",
            "types": [
                "administrative_area_level_1",
                "political"
            ]
        },
        {
            "long_name": "United Kingdom",
            "short_name": "GB",
            "types": [
                "country",
                "political"
            ]
        },
        {
            "long_name": "W1K 2PU",
            "short_name": "W1K 2PU",
            "types": [
                "postal_code"
            ]
        }
    ]
}

which is a subset of the response obtained querying the Google Geocoding service as described here

I would like to apply a couple of json path queries to be able to rebuild the address components elements into a multiline string like the following

43a S Audley St
London W1K 2PU
United Kingdom

Based on these answers #1, #2, I know I am able to apply filtering and expressions. Also, based on this page, I've learned that I can use the in operator to filter on the types attribute.

However all my attempts did not succeded. Any help?

Upvotes: 0

Views: 38

Answers (1)

wp78de
wp78de

Reputation: 19000

It would be important to know what tool or service you apply the jsonpath and what JsonPath implementation is at play. If you work in a JavaScript-based environment it is highly likely that could use a JS-script eval workaround to get there, e.g.

$.address_components[?(/street_number|route|postal_code|country/i.test(@.types))].long_name

Which outputs:

[
    "43a",
    "South Audley Street",
    "United Kingdom",
    "W1K 2PU"
]

Test it here. However, you are most likely better off using your host programming to build the string based on (full) JSON or using a tool like jq.

Upvotes: 0

Related Questions