Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select multiple attributes with jsonpath

Tags:

json

jsonpath

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

like image 753
mnieto Avatar asked Oct 23 '18 13:10

mnieto


1 Answers

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?

like image 162
B. Cratty Avatar answered Oct 06 '22 00:10

B. Cratty