Kamalakannan J
Kamalakannan J

Reputation: 2998

JSONata: How to get all paths from the payload?

How to get all the paths of the input object and traverse it according to my wish.

One such use case is I want to convert the value of all except few fields/nested fields in a object to uppercase.

For example, assume below is the input,

{
  "name": "John",
    "age": 30,
    "bio": "I am a software developer.",
    "username": "john_doe",
    "profiles": [
        {
            "network": "Twitter",
            "username": "john_doe"
        },
        {
            "network": "Facebook",
            "username": "john_doe"
        }
    ]
}

For the above payload, I want to convert all values to uppercase, except for $.username and $.profiles.username. In this case, I would know only which are those fields to except, not the paths to convert.

Output for above would be,


{
  "name": "JOHN",
    "age": 30,
    "bio": "I AM A SOFTWARE DEVELOPER.",
    "username": "john_doe",
    "profiles": [
        {
            "network": "TWITTER",
            "username": "john_doe"
        },
        {
            "network": "FACEBOOK",
            "username": "john_doe"
        }
    ]
}

How to achieve this using JSONata ?

Upvotes: 0

Views: 292

Answers (1)

mralex
mralex

Reputation: 1090

You can write a recursive function to dig deep into your object and then replace values that match your criteria:

(
  $recurse := function($object) {
    (
      $type($object) = "object"
        ? $merge($each($object, function($value, $key) { 
            { 
              $key: $type($value) = "string" and $key != "username"
                ? $uppercase($value)
                : $recurse($value)
            } 
          }))
        : $type($object) = "array"
          ? $map($object, $recurse)
          : $object
    )
  };

  $recurse($)
)

Check it out on the Stedi playground: https://stedi.link/HYL5ebO

Upvotes: 0

Related Questions