26

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": "mail@myorganization.com",
        "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" : "mail@myorganization.com",
      "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

mnieto
  • 3,744
  • 4
  • 21
  • 37

1 Answers1

8

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 to pull the base code I used to come up with this from here, https://stackoverflow.com/questions/33473571/how-to-extract-a-json-subset-from-main-json

I don't know if this will exactly work, but I was hoping it would at least 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 your own object?

rockingskier
  • 9,066
  • 3
  • 40
  • 49
B. Cratty
  • 1,725
  • 1
  • 17
  • 32