select multiple attributes with jsonpath

mnieto picture mnieto · Oct 23, 2018 · Viewed 10.2k times · Source

I have an array of objects like this one:

[
    {
        "id": 192,
        "name": "Complete name",
        "username": "nsurname",
        "state": "active",
        "created_at": "2016-05-30T07:09:40.981Z",
        "organization": "",
        "last_sign_in_at": "2018-10-19T12:07:50.679Z",
        "confirmed_at": "2016-05-30T07:09:40.982Z",
        "last_activity_on": "2018-10-15",
        "email": "[email protected]",
        "current_sign_in_at": "2018-10-23T11:41:27.880Z",
        "identities": [
            {
                "provider": "ldapmain",
                "extern_uid": "user distinguished name"
            }
        ],
        "can_create_group": true,
        "can_create_project": false
    }
]

What I want is extract only a subset of attributes and get something like this:

[
   {
      "id" : 192,
      "name" : "complete name",
      "username" : "uname",
      "email" : "[email protected]",
      "extern_uid": "user distinguished name"
   }
]

Based on this answer, I successfully got id, name, username and email attributes with this expression using Jayway JsonPath Evaluator at http://jsonpath.herokuapp.com/

$..['id', 'name', 'username', 'email']

But how can I get an attribute of different level? extern_uid

Answer

B. Cratty picture B. Cratty · Oct 23, 2018

I would have put this in the comments but I thought this would be easier to read. You could just parse the answer and then use Stringify to recreate the JSON object that you want. I was able pull the base code I used to come up with this from here, How to extract a JSON subset from main JSON

I don't know if this will exactly work, but I was hoping it would atleast point you down the right rode to finding the solution.

My Answer:

var parsed = JSON.parse(thisObjectYouLinked);//here you would put whatever JSON object you displayed

var newObject = JSON.stringify({
    $..['id', 'name', 'username', 'email']
    $.identies[*].['extern_uid']
});

So long story short instead of trying to figure out the JSONPath stuff, why not just parse and create youre own object?