kandi background
Explore Kits

JsonPath | Java JsonPath implementation | JSON Processing library

 by   json-path Java Version: json-path-2.6.0 License: Apache-2.0

 by   json-path Java Version: json-path-2.6.0 License: Apache-2.0

Download this library from

kandi X-RAY | JsonPath Summary

JsonPath is a Java library typically used in Utilities, JSON Processing applications. JsonPath has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has medium support. You can download it from GitHub.
Java JsonPath implementation
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • JsonPath has a medium active ecosystem.
  • It has 6204 star(s) with 1166 fork(s). There are 282 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 198 open issues and 263 have been closed. On average issues are closed in 167 days. There are 48 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of JsonPath is json-path-2.6.0
JsonPath Support
Best in #JSON Processing
Average in #JSON Processing
JsonPath Support
Best in #JSON Processing
Average in #JSON Processing

quality kandi Quality

  • JsonPath has 0 bugs and 0 code smells.
JsonPath Quality
Best in #JSON Processing
Average in #JSON Processing
JsonPath Quality
Best in #JSON Processing
Average in #JSON Processing

securitySecurity

  • JsonPath has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • JsonPath code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
JsonPath Security
Best in #JSON Processing
Average in #JSON Processing
JsonPath Security
Best in #JSON Processing
Average in #JSON Processing

license License

  • JsonPath is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
JsonPath License
Best in #JSON Processing
Average in #JSON Processing
JsonPath License
Best in #JSON Processing
Average in #JSON Processing

buildReuse

  • JsonPath releases are available to install and integrate.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • JsonPath saves you 7488 person hours of effort in developing the same functionality from scratch.
  • It has 15949 lines of code, 1788 functions and 187 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
JsonPath Reuse
Best in #JSON Processing
Average in #JSON Processing
JsonPath Reuse
Best in #JSON Processing
Average in #JSON Processing
Top functions reviewed by kandi - BETA

kandi has reviewed JsonPath and discovered the below as its top functions. This is intended to give you an instant insight into JsonPath implemented functionality, and help decide if they suit your requirements.

  • Parse the function parameters .
  • Pretty print a string .
  • Handles an object property .
  • Escapes the given string .
  • Returns the index of the first matching close char in the given start character .
  • Invokes the inner model .
  • Sets value in given object node
  • Performs mapping on a JSON object .
  • Reads a path .
  • Inverts the given path to the function parameter .

JsonPath Key Features

Java JsonPath implementation

default

copy iconCopydownload iconDownload
02 Jun 2021 - Released JsonPath 2.6.0

10 Dec 2020 - Released JsonPath 2.5.0

05 Jul 2017 - Released JsonPath 2.4.0

26 Jun 2017 - Released JsonPath 2.3.0

29 Feb 2016 - Released JsonPath 2.2.0

22 Nov 2015 - Released JsonPath 2.1.0

19 Mar 2015 - Released JsonPath 2.0.0

11 Nov 2014 - Released JsonPath 1.2.0

01 Oct 2014 - Released JsonPath 1.1.0

26 Sep 2014 - Released JsonPath 1.0.0


Getting Started
---------------

JsonPath is available at the Central Maven Repository. Maven users add this to your POM.

```xml
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.6.0</version>
</dependency>
```

If you need help ask questions at [Stack Overflow](http://stackoverflow.com/questions/tagged/jsonpath). Tag the question 'jsonpath' and 'java'.

JsonPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination
with an XML document. The "root member object" in JsonPath is always referred to as `$` regardless if it is an
object or array.

JsonPath expressions can use the dot–notation

`$.store.book[0].title`

or the bracket–notation

`$['store']['book'][0]['title']`

Operators
---------

| Operator                  | Description                                                        |
| :------------------------ | :----------------------------------------------------------------- |
| `$`                       | The root element to query. This starts all path expressions.       |
| `@`                       | The current node being processed by a filter predicate.            |
| `*`                       | Wildcard. Available anywhere a name or numeric are required.       |
| `..`                      | Deep scan. Available anywhere a name is required.                  |
| `.<name>`                 | Dot-notated child                                                  |
| `['<name>' (, '<name>')]` | Bracket-notated child or children                                  |
| `[<number> (, <number>)]` | Array index or indexes                                             |
| `[start:end]`             | Array slice operator                                               |
| `[?(<expression>)]`       | Filter expression. Expression must evaluate to a boolean value.    |


Functions
---------

Functions can be invoked at the tail end of a path - the input to a function is the output of the path expression.
The function output is dictated by the function itself.

| Function                  | Description                                                         | Output type |
| :------------------------ | :------------------------------------------------------------------ |:----------- |
| min()                     | Provides the min value of an array of numbers                       | Double      |
| max()                     | Provides the max value of an array of numbers                       | Double      |
| avg()                     | Provides the average value of an array of numbers                   | Double      |
| stddev()                  | Provides the standard deviation value of an array of numbers        | Double      |
| length()                  | Provides the length of an array                                     | Integer     |
| sum()                     | Provides the sum value of an array of numbers                       | Double      |
| keys()                    | Provides the property keys (An alternative for terminal tilde `~`)  | `Set<E>`    |
| concat(X)                 | Provides a concatinated version of the path output with a new item  | like input  |
| append(X)                 | add an item to the json path output array                           | like input  |

Filter Operators
-----------------

Filters are logical expressions used to filter arrays. A typical filter would be `[?(@.age > 18)]` where `@` represents the current item being processed. More complex filters can be created with logical operators `&&` and `||`. String literals must be enclosed by single or double quotes (`[?(@.color == 'blue')]` or `[?(@.color == "blue")]`).

| Operator                 | Description                                                           |
| :----------------------- | :-------------------------------------------------------------------- |
| ==                       | left is equal to right (note that 1 is not equal to '1')              |
| !=                       | left is not equal to right                                            |
| <                        | left is less than right                                               |
| <=                       | left is less or equal to right                                        |
| >                        | left is greater than right                                            |
| >=                       | left is greater than or equal to right                                |
| =~                       | left matches regular expression  [?(@.name =~ /foo.*?/i)]             |
| in                       | left exists in right [?(@.size in ['S', 'M'])]                        |
| nin                      | left does not exists in right                                         |
| subsetof                 | left is a subset of right [?(@.sizes subsetof ['S', 'M', 'L'])]       |
| anyof                    | left has an intersection with right [?(@.sizes anyof ['M', 'L'])]     |
| noneof                   | left has no intersection with right [?(@.sizes noneof ['M', 'L'])]    |
| size                     | size of left (array or string) should match right                     |
| empty                    | left (array or string) should be empty                                |


Path Examples
-------------

Given the json

```javascript
{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}
```

| JsonPath (click link to try)| Result |
| :------- | :----- |
| <a href="http://jsonpath.herokuapp.com/?path=$.store.book[*].author" target="_blank">$.store.book[*].author</a>| The authors of all books     |
| <a href="http://jsonpath.herokuapp.com/?path=$..author" target="_blank">$..author</a>                   | All authors                         |
| <a href="http://jsonpath.herokuapp.com/?path=$.store.*" target="_blank">$.store.*</a>                  | All things, both books and bicycles  |
| <a href="http://jsonpath.herokuapp.com/?path=$.store..price" target="_blank">$.store..price</a>             | The price of everything         |
| <a href="http://jsonpath.herokuapp.com/?path=$..book[2]" target="_blank">$..book[2]</a>                 | The third book                      |
| <a href="http://jsonpath.herokuapp.com/?path=$..book[2]" target="_blank">$..book[-2]</a>                 | The second to last book            |
| <a href="http://jsonpath.herokuapp.com/?path=$..book[0,1]" target="_blank">$..book[0,1]</a>               | The first two books               |
| <a href="http://jsonpath.herokuapp.com/?path=$..book[:2]" target="_blank">$..book[:2]</a>                | All books from index 0 (inclusive) until index 2 (exclusive) |
| <a href="http://jsonpath.herokuapp.com/?path=$..book[1:2]" target="_blank">$..book[1:2]</a>                | All books from index 1 (inclusive) until index 2 (exclusive) |
| <a href="http://jsonpath.herokuapp.com/?path=$..book[-2:]" target="_blank">$..book[-2:]</a>                | Last two books                   |
| <a href="http://jsonpath.herokuapp.com/?path=$..book[2:]" target="_blank">$..book[2:]</a>                | Book number two from tail          |
| <a href="http://jsonpath.herokuapp.com/?path=$..book[?(@.isbn)]" target="_blank">$..book[?(@.isbn)]</a>          | All books with an ISBN number         |
| <a href="http://jsonpath.herokuapp.com/?path=$.store.book[?(@.price < 10)]" target="_blank">$.store.book[?(@.price < 10)]</a> | All books in store cheaper than 10  |
| <a href="http://jsonpath.herokuapp.com/?path=$..book[?(@.price <= $['expensive'])]" target="_blank">$..book[?(@.price <= $['expensive'])]</a> | All books in store that are not "expensive"  |
| <a href="http://jsonpath.herokuapp.com/?path=$..book[?(@.author =~ /.*REES/i)]" target="_blank">$..book[?(@.author =~ /.*REES/i)]</a> | All books matching regex (ignore case)  |
| <a href="http://jsonpath.herokuapp.com/?path=$..*" target="_blank">$..*</a>                        | Give me every thing
| <a href="http://jsonpath.herokuapp.com/?path=$..book.length()" target="_blank">$..book.length()</a>                 | The number of books                      |

Reading a Document
------------------
The simplest most straight forward way to use JsonPath is via the static read API.

```java
String json = "...";

List<String> authors = JsonPath.read(json, "$.store.book[*].author");
```

If you only want to read once this is OK. In case you need to read an other path as well this is not the way
to go since the document will be parsed every time you call JsonPath.read(...). To avoid the problem you can
parse the json first.

```java
String json = "...";
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);

String author0 = JsonPath.read(document, "$.store.book[0].author");
String author1 = JsonPath.read(document, "$.store.book[1].author");
```
JsonPath also provides a fluent API. This is also the most flexible one.

```java
String json = "...";

ReadContext ctx = JsonPath.parse(json);

List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");


List<Map<String, Object>> expensiveBooks = JsonPath
                            .using(configuration)
                            .parse(json)
                            .read("$.store.book[?(@.price > 10)]", List.class);
```

What is Returned When?
----------------------
When using JsonPath in java its important to know what type you expect in your result. JsonPath will automatically
try to cast the result to the type expected by the invoker.

```java
//Will throw an java.lang.ClassCastException
List<String> list = JsonPath.parse(json).read("$.store.book[0].author")

//Works fine
String author = JsonPath.parse(json).read("$.store.book[0].author")
```

When evaluating a path you need to understand the concept of when a path is `definite`. A path is `indefinite` if it contains:

* `..` - a deep scan operator
* `?(<expression>)` - an expression
* `[<number>, <number> (, <number>)]` - multiple array indexes

`Indefinite` paths always returns a list (as represented by current JsonProvider).

By default a simple object mapper is provided by the MappingProvider SPI. This allows you to specify the return type you want and the MappingProvider will
try to perform the mapping. In the example below mapping between `Long` and `Date` is demonstrated.

```java
String json = "{\"date_as_long\" : 1411455611975}";

Date date = JsonPath.parse(json).read("$['date_as_long']", Date.class);
```

If you configure JsonPath to use `JacksonMappingProvider` or `GsonMappingProvider` you can even map your JsonPath output directly into POJO's.

```java
Book book = JsonPath.parse(json).read("$.store.book[0]", Book.class);
```

To obtain full generics type information, use TypeRef.

```java
TypeRef<List<String>> typeRef = new TypeRef<List<String>>() {};

List<String> titles = JsonPath.parse(JSON_DOCUMENT).read("$.store.book[*].title", typeRef);
```

Predicates
----------
There are three different ways to create filter predicates in JsonPath.

### Inline Predicates

Inline predicates are the ones defined in the path.

```java
List<Map<String, Object>> books =  JsonPath.parse(json)
                                     .read("$.store.book[?(@.price < 10)]");
```

You can use `&&` and `||` to combine multiple predicates `[?(@.price < 10 && @.category == 'fiction')]` ,
`[?(@.category == 'reference' || @.price > 10)]`.

You can use `!` to negate a predicate `[?(!(@.price < 10 && @.category == 'fiction'))]`.

### Filter Predicates

Predicates can be built using the Filter API as shown below:

```java
import static com.jayway.jsonpath.JsonPath.parse;
import static com.jayway.jsonpath.Criteria.where;
import static com.jayway.jsonpath.Filter.filter;
...
...

Filter cheapFictionFilter = filter(
   where("category").is("fiction").and("price").lte(10D)
);

List<Map<String, Object>> books =
   parse(json).read("$.store.book[?]", cheapFictionFilter);

```
Notice the placeholder `?` for the filter in the path. When multiple filters are provided they are applied in order where the number of placeholders must match
the number of provided filters. You can specify multiple predicate placeholders in one filter operation `[?, ?]`, both predicates must match.

Filters can also be combined with 'OR' and 'AND'
```java
Filter fooOrBar = filter(
   where("foo").exists(true)).or(where("bar").exists(true)
);

Filter fooAndBar = filter(
   where("foo").exists(true)).and(where("bar").exists(true)
);
```

### Roll Your Own

Third option is to implement your own predicates

```java
Predicate booksWithISBN = new Predicate() {
    @Override
    public boolean apply(PredicateContext ctx) {
        return ctx.item(Map.class).containsKey("isbn");
    }
};

List<Map<String, Object>> books =
   reader.read("$.store.book[?].isbn", List.class, booksWithISBN);
```

Path vs Value
-------------
In the Goessner implementation a JsonPath can return either `Path` or `Value`. `Value` is the default and what all the examples above are returning. If you rather have the path of the elements our query is hitting this can be achieved with an option.

```java
Configuration conf = Configuration.builder()
   .options(Option.AS_PATH_LIST).build();

List<String> pathList = using(conf).parse(json).read("$..author");

assertThat(pathList).containsExactly(
    "$['store']['book'][0]['author']",
    "$['store']['book'][1]['author']",
    "$['store']['book'][2]['author']",
    "$['store']['book'][3]['author']");
```

Set a value
-----------
The library offers the possibility to set a value.

```java
String newJson = JsonPath.parse(json).set("$['store']['book'][0]['author']", "Paul").jsonString();
```



Tweaking Configuration
----------------------

### Options
When creating your Configuration there are a few option flags that can alter the default behaviour.

**DEFAULT_PATH_LEAF_TO_NULL**
<br/>
This option makes JsonPath return null for missing leafs. Consider the following json

```javascript
[
   {
      "name" : "john",
      "gender" : "male"
   },
   {
      "name" : "ben"
   }
]
```

```java
Configuration conf = Configuration.defaultConfiguration();

//Works fine
String gender0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");
//PathNotFoundException thrown
String gender1 = JsonPath.using(conf).parse(json).read("$[1]['gender']");

Configuration conf2 = conf.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);

//Works fine
String gender0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
//Works fine (null is returned)
String gender1 = JsonPath.using(conf2).parse(json).read("$[1]['gender']");
```

**ALWAYS_RETURN_LIST**
<br/>
This option configures JsonPath to return a list even when the path is `definite`.

```java
Configuration conf = Configuration.defaultConfiguration();

//ClassCastException thrown
List<String> genders0 = JsonPath.using(conf).parse(json).read("$[0]['gender']");

Configuration conf2 = conf.addOptions(Option.ALWAYS_RETURN_LIST);

//Works fine
List<String> genders0 = JsonPath.using(conf2).parse(json).read("$[0]['gender']");
```
**SUPPRESS_EXCEPTIONS**
<br/>
This option makes sure no exceptions are propagated from path evaluation. It follows these simple rules:

* If option `ALWAYS_RETURN_LIST` is present an empty list will be returned
* If option `ALWAYS_RETURN_LIST` is **NOT** present null returned

**REQUIRE_PROPERTIES**
</br>
This option configures JsonPath to require properties defined in path when an `indefinite` path is evaluated.

```java
Configuration conf = Configuration.defaultConfiguration();

//Works fine
List<String> genders = JsonPath.using(conf).parse(json).read("$[*]['gender']");

Configuration conf2 = conf.addOptions(Option.REQUIRE_PROPERTIES);

//PathNotFoundException thrown
List<String> genders = JsonPath.using(conf2).parse(json).read("$[*]['gender']");
```

### JsonProvider SPI

JsonPath is shipped with five different JsonProviders:

* [JsonSmartJsonProvider](https://code.google.com/p/json-smart/) (default)
* [JacksonJsonProvider](https://github.com/FasterXML/jackson)
* [JacksonJsonNodeJsonProvider](https://github.com/FasterXML/jackson)
* [GsonJsonProvider](https://code.google.com/p/google-gson/)
* [JsonOrgJsonProvider](http://www.json.org/java/index.html)

Changing the configuration defaults as demonstrated should only be done when your application is being initialized. Changes during runtime is strongly discouraged, especially in multi threaded applications.


```java
Configuration.setDefaults(new Configuration.Defaults() {

    private final JsonProvider jsonProvider = new JacksonJsonProvider();
    private final MappingProvider mappingProvider = new JacksonMappingProvider();

    @Override
    public JsonProvider jsonProvider() {
        return jsonProvider;
    }

    @Override
    public MappingProvider mappingProvider() {
        return mappingProvider;
    }

    @Override
    public Set<Option> options() {
        return EnumSet.noneOf(Option.class);
    }
});
```

Note that the JacksonJsonProvider requires `com.fasterxml.jackson.core:jackson-databind:2.4.5` and the GsonJsonProvider requires `com.google.code.gson:gson:2.3.1` on your classpath.

### Cache SPI

In JsonPath 2.1.0 a new Cache SPI was introduced. This allows API consumers to configure path caching in a way that suits their needs. The cache must be configured before it is accesses for the first time or a JsonPathException is thrown. JsonPath ships with two cache implementations

* `com.jayway.jsonpath.spi.cache.LRUCache` (default, thread safe)
* `com.jayway.jsonpath.spi.cache.NOOPCache` (no cache)

If you want to implement your own cache the API is simple.

```java
CacheProvider.setCache(new Cache() {
    //Not thread safe simple cache
    private Map<String, JsonPath> map = new HashMap<String, JsonPath>();

    @Override
    public JsonPath get(String key) {
        return map.get(key);
    }

    @Override
    public void put(String key, JsonPath jsonPath) {
        map.put(key, jsonPath);
    }
});
```






[![Analytics](https://ga-beacon.appspot.com/UA-54945131-1/jsonpath/index)](https://github.com/igrigorik/ga-beacon)

delete the JSON object from one json object by comparing the id from another json object if id is not present in javascript/ node js

copy iconCopydownload iconDownload
// find items with `id` proerty
let objs = jsonpath.nodes(acc, '$..[?(@.sys.id)]');

// delete the items
objs.forEach(function(node) {
  let key = node.path.pop();
  let parent = jsonpath.value(acc, jsonpath.stringify(node.path));
  if (Array.isArray(parent))
    parent.splice(key, 1);
  else
    delete parent[key];
}, this);
let data = getData();
let anotherObj = getAnotherObj();

let res = data.reduce((acc, curr) => {
  if (!acc[curr.system.name]) {
    acc[curr.system.name] = {};
  }

  let detailsObj = {};
  Object.keys(curr.DataDetails).forEach(key => {
    let values = curr.DataDetails[key];

    // special handling to flatten single attribute objects
    if (values.length === undefined || values.length === 0) {
      let keys = Object.keys(values);
      if (keys.length == 1 && typeof values[keys[0]] !== 'object') {
        detailsObj[key] = values[keys[0]];
        return;
      }
    }

    // clone values to output
    detailsObj[key] = !Array.isArray(values) ? Object.assign({}, values) : [...values];

    // find and replace ids
    let ids = jsonpath.query(detailsObj[key], '$..id');
    ids.forEach((id, i) => {
      if (id in anotherObj) {
        if (Array.isArray(detailsObj[key]))
          detailsObj[key].splice(i, 1, anotherObj[id]);
        else
          detailsObj[key] = anotherObj[id];
      }
    });
  });

  acc[curr.system.name][curr.system.id] = {
    title: curr.system.id,
    uid: curr.system.id,
    url: `/${curr.system.name}/${curr.system.id}`,
    ...detailsObj,
  };

  // find items which were not replaced
  let objs = jsonpath.nodes(acc, '$..[?(@.sys.id)]');

  // delete the items
  objs.forEach(function(node) {
    let key = node.path.pop();
    let parent = jsonpath.value(acc, jsonpath.stringify(node.path));
    if (Array.isArray(parent))
      parent.splice(key, 1);
    else
      delete parent[key];
  }, this);

  return acc;
}, {});



document.body.insertAdjacentHTML('beforeend', `<pre>${JSON.stringify(res, undefined, 1)}</pre>`);
console.log(res);

function getData() {
  return [{
      system: {
        id: "4gSSbjCFEorYXqrgDIP2FA",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        shortOption: {
          "en-us": "some value"
        },
        mediaFile: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "7kRzyt4PFo",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "2OspeCtNK0s",
            },
          },
        ],
        mediaGalary: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              linkType: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],

      },
    },
    {
      system: {
        id: "1aBOO8tu3lUsjtICuIbUM5",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        short: {
          "en-us": "details of shorts"
        },
        shortSlugOption: {
          "hi-In": "options"
        },
        booleanField: {
          kl: "true"
        },
      },
    },
    {
      system: {
        id: "2pOUGnI1oRD7nsrYs600HA",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: [{
            sys: {
              type: "Link",
              link: "Entry",
              id: "66rzYr2BpWL",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Entry",
              id: "1VTBHdLTdSW",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "66rzYr2BpWL1VTBHdLTdSW",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        oneReference: {
          sys: {
            type: "Link",
            linkType: "Asset",
            id: "h2cPiuU9jIz",
          },
        },
        multiReference: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "cIb5mqEBRWDD6hrNmFmFE",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        testingNewValue: {
          "hi-IN": "jksdsdo"
        }
      },
    },
    {
      system: {
        id: "7kRzyt4PFrX13gHcw3Z1Ko",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: {
          "en-us": "kknksdo"
        }
      },
    }
  ];
}


function getAnotherObj() {
  return {
    "h2cPiuU9jIz": {
      status: true,
      tag: [],
      filename: "wallpapers-6.jpg",
      is_dir: false,
      parent_uid: null,
    },


    "2OspeCtNK0s": {
      status: true,
      tag: [],
      filename: "mediaFile1.jpg",
      is_dir: false,
      parent_uid: null,
    },
    "66rzYr2BpWL": {
      type: 'entry',
      tag: [],
      entry_details: "this is first entry ***",
      is_secret: false,
    },
    "1VTBHdLTdSW": {
      type: 'entry',
      tag: [],
      entry_details: "some other entry ***",
      is_secret: true,
    },
  };
}
<script src="https://cdn.jsdelivr.net/npm/jsonpath@1.1.1/jsonpath.min.js"></script>
-----------------------
// find items with `id` proerty
let objs = jsonpath.nodes(acc, '$..[?(@.sys.id)]');

// delete the items
objs.forEach(function(node) {
  let key = node.path.pop();
  let parent = jsonpath.value(acc, jsonpath.stringify(node.path));
  if (Array.isArray(parent))
    parent.splice(key, 1);
  else
    delete parent[key];
}, this);
let data = getData();
let anotherObj = getAnotherObj();

let res = data.reduce((acc, curr) => {
  if (!acc[curr.system.name]) {
    acc[curr.system.name] = {};
  }

  let detailsObj = {};
  Object.keys(curr.DataDetails).forEach(key => {
    let values = curr.DataDetails[key];

    // special handling to flatten single attribute objects
    if (values.length === undefined || values.length === 0) {
      let keys = Object.keys(values);
      if (keys.length == 1 && typeof values[keys[0]] !== 'object') {
        detailsObj[key] = values[keys[0]];
        return;
      }
    }

    // clone values to output
    detailsObj[key] = !Array.isArray(values) ? Object.assign({}, values) : [...values];

    // find and replace ids
    let ids = jsonpath.query(detailsObj[key], '$..id');
    ids.forEach((id, i) => {
      if (id in anotherObj) {
        if (Array.isArray(detailsObj[key]))
          detailsObj[key].splice(i, 1, anotherObj[id]);
        else
          detailsObj[key] = anotherObj[id];
      }
    });
  });

  acc[curr.system.name][curr.system.id] = {
    title: curr.system.id,
    uid: curr.system.id,
    url: `/${curr.system.name}/${curr.system.id}`,
    ...detailsObj,
  };

  // find items which were not replaced
  let objs = jsonpath.nodes(acc, '$..[?(@.sys.id)]');

  // delete the items
  objs.forEach(function(node) {
    let key = node.path.pop();
    let parent = jsonpath.value(acc, jsonpath.stringify(node.path));
    if (Array.isArray(parent))
      parent.splice(key, 1);
    else
      delete parent[key];
  }, this);

  return acc;
}, {});



document.body.insertAdjacentHTML('beforeend', `<pre>${JSON.stringify(res, undefined, 1)}</pre>`);
console.log(res);

function getData() {
  return [{
      system: {
        id: "4gSSbjCFEorYXqrgDIP2FA",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        shortOption: {
          "en-us": "some value"
        },
        mediaFile: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "7kRzyt4PFo",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "2OspeCtNK0s",
            },
          },
        ],
        mediaGalary: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              linkType: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],

      },
    },
    {
      system: {
        id: "1aBOO8tu3lUsjtICuIbUM5",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        short: {
          "en-us": "details of shorts"
        },
        shortSlugOption: {
          "hi-In": "options"
        },
        booleanField: {
          kl: "true"
        },
      },
    },
    {
      system: {
        id: "2pOUGnI1oRD7nsrYs600HA",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: [{
            sys: {
              type: "Link",
              link: "Entry",
              id: "66rzYr2BpWL",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Entry",
              id: "1VTBHdLTdSW",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "66rzYr2BpWL1VTBHdLTdSW",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        oneReference: {
          sys: {
            type: "Link",
            linkType: "Asset",
            id: "h2cPiuU9jIz",
          },
        },
        multiReference: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "cIb5mqEBRWDD6hrNmFmFE",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        testingNewValue: {
          "hi-IN": "jksdsdo"
        }
      },
    },
    {
      system: {
        id: "7kRzyt4PFrX13gHcw3Z1Ko",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: {
          "en-us": "kknksdo"
        }
      },
    }
  ];
}


function getAnotherObj() {
  return {
    "h2cPiuU9jIz": {
      status: true,
      tag: [],
      filename: "wallpapers-6.jpg",
      is_dir: false,
      parent_uid: null,
    },


    "2OspeCtNK0s": {
      status: true,
      tag: [],
      filename: "mediaFile1.jpg",
      is_dir: false,
      parent_uid: null,
    },
    "66rzYr2BpWL": {
      type: 'entry',
      tag: [],
      entry_details: "this is first entry ***",
      is_secret: false,
    },
    "1VTBHdLTdSW": {
      type: 'entry',
      tag: [],
      entry_details: "some other entry ***",
      is_secret: true,
    },
  };
}
<script src="https://cdn.jsdelivr.net/npm/jsonpath@1.1.1/jsonpath.min.js"></script>
-----------------------
// find items with `id` proerty
let objs = jsonpath.nodes(acc, '$..[?(@.sys.id)]');

// delete the items
objs.forEach(function(node) {
  let key = node.path.pop();
  let parent = jsonpath.value(acc, jsonpath.stringify(node.path));
  if (Array.isArray(parent))
    parent.splice(key, 1);
  else
    delete parent[key];
}, this);
let data = getData();
let anotherObj = getAnotherObj();

let res = data.reduce((acc, curr) => {
  if (!acc[curr.system.name]) {
    acc[curr.system.name] = {};
  }

  let detailsObj = {};
  Object.keys(curr.DataDetails).forEach(key => {
    let values = curr.DataDetails[key];

    // special handling to flatten single attribute objects
    if (values.length === undefined || values.length === 0) {
      let keys = Object.keys(values);
      if (keys.length == 1 && typeof values[keys[0]] !== 'object') {
        detailsObj[key] = values[keys[0]];
        return;
      }
    }

    // clone values to output
    detailsObj[key] = !Array.isArray(values) ? Object.assign({}, values) : [...values];

    // find and replace ids
    let ids = jsonpath.query(detailsObj[key], '$..id');
    ids.forEach((id, i) => {
      if (id in anotherObj) {
        if (Array.isArray(detailsObj[key]))
          detailsObj[key].splice(i, 1, anotherObj[id]);
        else
          detailsObj[key] = anotherObj[id];
      }
    });
  });

  acc[curr.system.name][curr.system.id] = {
    title: curr.system.id,
    uid: curr.system.id,
    url: `/${curr.system.name}/${curr.system.id}`,
    ...detailsObj,
  };

  // find items which were not replaced
  let objs = jsonpath.nodes(acc, '$..[?(@.sys.id)]');

  // delete the items
  objs.forEach(function(node) {
    let key = node.path.pop();
    let parent = jsonpath.value(acc, jsonpath.stringify(node.path));
    if (Array.isArray(parent))
      parent.splice(key, 1);
    else
      delete parent[key];
  }, this);

  return acc;
}, {});



document.body.insertAdjacentHTML('beforeend', `<pre>${JSON.stringify(res, undefined, 1)}</pre>`);
console.log(res);

function getData() {
  return [{
      system: {
        id: "4gSSbjCFEorYXqrgDIP2FA",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        shortOption: {
          "en-us": "some value"
        },
        mediaFile: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "7kRzyt4PFo",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "2OspeCtNK0s",
            },
          },
        ],
        mediaGalary: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              linkType: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],

      },
    },
    {
      system: {
        id: "1aBOO8tu3lUsjtICuIbUM5",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        short: {
          "en-us": "details of shorts"
        },
        shortSlugOption: {
          "hi-In": "options"
        },
        booleanField: {
          kl: "true"
        },
      },
    },
    {
      system: {
        id: "2pOUGnI1oRD7nsrYs600HA",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: [{
            sys: {
              type: "Link",
              link: "Entry",
              id: "66rzYr2BpWL",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Entry",
              id: "1VTBHdLTdSW",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "66rzYr2BpWL1VTBHdLTdSW",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        oneReference: {
          sys: {
            type: "Link",
            linkType: "Asset",
            id: "h2cPiuU9jIz",
          },
        },
        multiReference: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "cIb5mqEBRWDD6hrNmFmFE",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        testingNewValue: {
          "hi-IN": "jksdsdo"
        }
      },
    },
    {
      system: {
        id: "7kRzyt4PFrX13gHcw3Z1Ko",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: {
          "en-us": "kknksdo"
        }
      },
    }
  ];
}


function getAnotherObj() {
  return {
    "h2cPiuU9jIz": {
      status: true,
      tag: [],
      filename: "wallpapers-6.jpg",
      is_dir: false,
      parent_uid: null,
    },


    "2OspeCtNK0s": {
      status: true,
      tag: [],
      filename: "mediaFile1.jpg",
      is_dir: false,
      parent_uid: null,
    },
    "66rzYr2BpWL": {
      type: 'entry',
      tag: [],
      entry_details: "this is first entry ***",
      is_secret: false,
    },
    "1VTBHdLTdSW": {
      type: 'entry',
      tag: [],
      entry_details: "some other entry ***",
      is_secret: true,
    },
  };
}
<script src="https://cdn.jsdelivr.net/npm/jsonpath@1.1.1/jsonpath.min.js"></script>

Any workaround for JSONPATH wildcard not supported in Spark SQL

copy iconCopydownload iconDownload
> spark-shell --jars "json-path-2.7.0.jar"                      
:
scala> import com.jayway.jsonpath.JsonPath
import com.jayway.jsonpath.JsonPath

scala> val r = JsonPath.read[net.minidev.json.JSONArray]("""
     | {"k":{"value":"abc"},
     |  "m":{"value":"def"}}
     | ""","$.*.value")
r: net.minidev.json.JSONArray = ["abc","def"]

scala> 

Get pods in Kubernetes where all containers are &quot;ready&quot; in one line using kubectl

copy iconCopydownload iconDownload
kubectl get po -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}{{range .items}}{{$pod := .}}{{range .status.containerStatuses}}{{if eq .ready false}}{{$pod.metadata.name}}{{"\n"}}{{end}}{{end}}{{end}}' | sort | uniq -u
-----------------------
kubectl get pod |grep -Po '^([^ ]+)(?=\s+((\d+)\/\3))'
kubectl get pod
NAME    READY   STATUS     RESTARTS        AGE
bar     2/2     Running    0               5m12s
foo     1/3     NotReady   6               6m9s
mypod   1/1     Running    2 (9m58s ago)   21h

kubectl get pod |grep -Po '^([^ ]+)(?=\s+((\d+)\/\3))'
bar
mypod
ps@controller:~$
-----------------------
kubectl get pod |grep -Po '^([^ ]+)(?=\s+((\d+)\/\3))'
kubectl get pod
NAME    READY   STATUS     RESTARTS        AGE
bar     2/2     Running    0               5m12s
foo     1/3     NotReady   6               6m9s
mypod   1/1     Running    2 (9m58s ago)   21h

kubectl get pod |grep -Po '^([^ ]+)(?=\s+((\d+)\/\3))'
bar
mypod
ps@controller:~$
-----------------------
kubectl get po -o go-template='{{ $readyFlag := true}}{{range .items}}{{range .status.containerStatuses}}{{ if not .ready}}{{ $readyFlag = false}}{{end}}{{end}}{{if $readyFlag }}{{.metadata.name}}{{"\n"}}{{end}}{{end}}'
kubectl get po -o go-template='{{ $readyFlag := true}}{{range .items}}{{range .status.containerStatuses}}{{ if not .ready}}{{ $readyFlag = false}}{{end}}{{end}}{{if not $readyFlag }}{{.metadata.name}}{{"\n"}}{{end}}{{end}}'
-----------------------
kubectl get po -o go-template='{{ $readyFlag := true}}{{range .items}}{{range .status.containerStatuses}}{{ if not .ready}}{{ $readyFlag = false}}{{end}}{{end}}{{if $readyFlag }}{{.metadata.name}}{{"\n"}}{{end}}{{end}}'
kubectl get po -o go-template='{{ $readyFlag := true}}{{range .items}}{{range .status.containerStatuses}}{{ if not .ready}}{{ $readyFlag = false}}{{end}}{{end}}{{if not $readyFlag }}{{.metadata.name}}{{"\n"}}{{end}}{{end}}'

Unable to use jsonpath function for output parameter in Argo Workflows

copy iconCopydownload iconDownload
           - name: dev-outputs
             depends: dev-create.Succeeded
             templateRef:
               name: dev-outputs-wft
               template: main
             arguments:
               parameters:
                 - name: devoutputs
-                   value: "{{=jsonpath(tasks.dev-create.outputs.parameters.devoutputs, '$.alias.value')}}"
+                   value: "{{=jsonpath(tasks['dev-create'].outputs.parameters.devoutputs, '$.alias.value')}}"

Error Mapping Geometry type Point in PostgreSQL

copy iconCopydownload iconDownload
spring:
 jpa:
   properties.hibernate.dialect: org.hibernate.spatial.dialect.postgis.PostgisDialect
   database-platform: org.hibernate.spatial.dialect.postgis.PostgisDialect
   hibernate:
      dialect: org.hibernate.spatial.dialect.postgis.PostgisDialect
-----------------------
@Column(name = "location", columnDefinition="geography")
private Point location;

Kubernetes CRD: Show durations in additionalPrinterColumns

copy iconCopydownload iconDownload
kubectl get job job-name --v=8
kubectl get job job-name --v=8 --server-print=false
-----------------------
kubectl get job job-name --v=8
kubectl get job job-name --v=8 --server-print=false

Unable to authenticate service account - Google Cloud

copy iconCopydownload iconDownload
// Please, set the appropriate path to your JSON credentials file here
String credentialsPath = "..."; 
// The credentials could be loaded as well as this.getClass().getResourceAsStream(), for example
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(credentialsPath))
    .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));

// Use that credentials to build your image annotation client
ImageAnnotatorSettings imageAnnotatorSettings =
  ImageAnnotatorSettings.newBuilder()
    .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
    .build()
;

ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create(imageAnnotatorSettings);
// Perform the stuff you need to...
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-vision</artifactId>
    <version>2.0.18</version>
</dependency>
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create();
-----------------------
// Please, set the appropriate path to your JSON credentials file here
String credentialsPath = "..."; 
// The credentials could be loaded as well as this.getClass().getResourceAsStream(), for example
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(credentialsPath))
    .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));

// Use that credentials to build your image annotation client
ImageAnnotatorSettings imageAnnotatorSettings =
  ImageAnnotatorSettings.newBuilder()
    .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
    .build()
;

ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create(imageAnnotatorSettings);
// Perform the stuff you need to...
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-vision</artifactId>
    <version>2.0.18</version>
</dependency>
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create();
-----------------------
// Please, set the appropriate path to your JSON credentials file here
String credentialsPath = "..."; 
// The credentials could be loaded as well as this.getClass().getResourceAsStream(), for example
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(credentialsPath))
    .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));

// Use that credentials to build your image annotation client
ImageAnnotatorSettings imageAnnotatorSettings =
  ImageAnnotatorSettings.newBuilder()
    .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
    .build()
;

ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create(imageAnnotatorSettings);
// Perform the stuff you need to...
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-vision</artifactId>
    <version>2.0.18</version>
</dependency>
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create();

How to mock JWT token to use it with Mockito and Spring Boot

copy iconCopydownload iconDownload
@AutoConfigureMockMvc(addFilters = false)
class CategoryCommandControllerTest {
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();
}
 if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    } else {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return;
    }
  if (username != null) {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        if (jwtUtil.validateToken(jwt, userDetails)) {

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            usernamePasswordAuthenticationToken
                    .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }

        // chain.doFilter(request, response);

    }

    chain.doFilter(request, response);

}
-----------------------
@AutoConfigureMockMvc(addFilters = false)
class CategoryCommandControllerTest {
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();
}
 if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    } else {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return;
    }
  if (username != null) {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        if (jwtUtil.validateToken(jwt, userDetails)) {

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            usernamePasswordAuthenticationToken
                    .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }

        // chain.doFilter(request, response);

    }

    chain.doFilter(request, response);

}
-----------------------
@AutoConfigureMockMvc(addFilters = false)
class CategoryCommandControllerTest {
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();
}
 if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    } else {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return;
    }
  if (username != null) {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        if (jwtUtil.validateToken(jwt, userDetails)) {

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            usernamePasswordAuthenticationToken
                    .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }

        // chain.doFilter(request, response);

    }

    chain.doFilter(request, response);

}
-----------------------
@AutoConfigureMockMvc(addFilters = false)
class CategoryCommandControllerTest {
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();
}
 if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    } else {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return;
    }
  if (username != null) {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        if (jwtUtil.validateToken(jwt, userDetails)) {

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            usernamePasswordAuthenticationToken
                    .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }

        // chain.doFilter(request, response);

    }

    chain.doFilter(request, response);

}
-----------------------
@MockBean
private JwtUtil jwtUtil;
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    }
@WebMvcTest(value = CategoryCommandController.class, includeFilters = {
        // to include JwtUtil in spring context
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = JwtUtil.class)})
class CategoryCommandControllerTest {

    Logger logger = LoggerFactory.getLogger(CategoryCommandController.class);

    @MockBean
    private CategoryCommandService categoryCommandService;

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MyUserDetailsService myUserDetailsService;

    @MockBean
    private CategoryRepository categoryRepository;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtRequestFilter filter;

    //    @WithMockUser
    @Test
    void testCreateCategory() throws Exception {

        CategoryCreateDto categoryCreateDto = new CategoryCreateDto("category");
        CategoryCreateDto categoryCreateResponseDto = new CategoryCreateDto(UUID.fromString("2da4002a-31c5-4cc7-9b92-cbf0db998c41"), "category");

        String jsonCreate = asJsonString(categoryCreateDto);
        String jsonResponse = asJsonString(categoryCreateResponseDto);
        UserDetails dummy = new User("foo@email.com", "foo", new ArrayList<>());
        String jwtToken = jwtUtil.generateToken(dummy);
        RequestBuilder request = MockMvcRequestBuilders
                .post("/api/adverts/category")
                .content(jsonCreate)
                .header("Authorization", "Bearer " + jwtToken)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .accept(MediaType.APPLICATION_JSON);
// Below line is not used
//        mockMvc.perform(request).andReturn();

        //             Should be createCategory(eq(categoryCreateDto))?
        when(categoryCommandService.createCategory(categoryCreateDto)).thenReturn(
                categoryCreateResponseDto);
        // Mock Service method used in JwtRequestFilter
        when(myUserDetailsService.loadUserByUsername(eq("foo@email.com"))).thenReturn(dummy);
        MvcResult mvcResult = mockMvc.perform(request)
                .andExpect(status().is2xxSuccessful())
//                .andExpect(content().json(jsonResponse, true))
                .andExpect(jsonPath("$.id").value("2da4002a-31c5-4cc7-9b92-cbf0db998c41"))
//                .andExpect(jsonPath("$.title").value("category"))
                .andReturn();

        logger.info(mvcResult.getResponse().getContentAsString());
    }
    ...
}
-----------------------
@MockBean
private JwtUtil jwtUtil;
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    }
@WebMvcTest(value = CategoryCommandController.class, includeFilters = {
        // to include JwtUtil in spring context
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = JwtUtil.class)})
class CategoryCommandControllerTest {

    Logger logger = LoggerFactory.getLogger(CategoryCommandController.class);

    @MockBean
    private CategoryCommandService categoryCommandService;

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MyUserDetailsService myUserDetailsService;

    @MockBean
    private CategoryRepository categoryRepository;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtRequestFilter filter;

    //    @WithMockUser
    @Test
    void testCreateCategory() throws Exception {

        CategoryCreateDto categoryCreateDto = new CategoryCreateDto("category");
        CategoryCreateDto categoryCreateResponseDto = new CategoryCreateDto(UUID.fromString("2da4002a-31c5-4cc7-9b92-cbf0db998c41"), "category");

        String jsonCreate = asJsonString(categoryCreateDto);
        String jsonResponse = asJsonString(categoryCreateResponseDto);
        UserDetails dummy = new User("foo@email.com", "foo", new ArrayList<>());
        String jwtToken = jwtUtil.generateToken(dummy);
        RequestBuilder request = MockMvcRequestBuilders
                .post("/api/adverts/category")
                .content(jsonCreate)
                .header("Authorization", "Bearer " + jwtToken)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .accept(MediaType.APPLICATION_JSON);
// Below line is not used
//        mockMvc.perform(request).andReturn();

        //             Should be createCategory(eq(categoryCreateDto))?
        when(categoryCommandService.createCategory(categoryCreateDto)).thenReturn(
                categoryCreateResponseDto);
        // Mock Service method used in JwtRequestFilter
        when(myUserDetailsService.loadUserByUsername(eq("foo@email.com"))).thenReturn(dummy);
        MvcResult mvcResult = mockMvc.perform(request)
                .andExpect(status().is2xxSuccessful())
//                .andExpect(content().json(jsonResponse, true))
                .andExpect(jsonPath("$.id").value("2da4002a-31c5-4cc7-9b92-cbf0db998c41"))
//                .andExpect(jsonPath("$.title").value("category"))
                .andReturn();

        logger.info(mvcResult.getResponse().getContentAsString());
    }
    ...
}
-----------------------
@MockBean
private JwtUtil jwtUtil;
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    }
@WebMvcTest(value = CategoryCommandController.class, includeFilters = {
        // to include JwtUtil in spring context
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = JwtUtil.class)})
class CategoryCommandControllerTest {

    Logger logger = LoggerFactory.getLogger(CategoryCommandController.class);

    @MockBean
    private CategoryCommandService categoryCommandService;

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MyUserDetailsService myUserDetailsService;

    @MockBean
    private CategoryRepository categoryRepository;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private JwtRequestFilter filter;

    //    @WithMockUser
    @Test
    void testCreateCategory() throws Exception {

        CategoryCreateDto categoryCreateDto = new CategoryCreateDto("category");
        CategoryCreateDto categoryCreateResponseDto = new CategoryCreateDto(UUID.fromString("2da4002a-31c5-4cc7-9b92-cbf0db998c41"), "category");

        String jsonCreate = asJsonString(categoryCreateDto);
        String jsonResponse = asJsonString(categoryCreateResponseDto);
        UserDetails dummy = new User("foo@email.com", "foo", new ArrayList<>());
        String jwtToken = jwtUtil.generateToken(dummy);
        RequestBuilder request = MockMvcRequestBuilders
                .post("/api/adverts/category")
                .content(jsonCreate)
                .header("Authorization", "Bearer " + jwtToken)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .accept(MediaType.APPLICATION_JSON);
// Below line is not used
//        mockMvc.perform(request).andReturn();

        //             Should be createCategory(eq(categoryCreateDto))?
        when(categoryCommandService.createCategory(categoryCreateDto)).thenReturn(
                categoryCreateResponseDto);
        // Mock Service method used in JwtRequestFilter
        when(myUserDetailsService.loadUserByUsername(eq("foo@email.com"))).thenReturn(dummy);
        MvcResult mvcResult = mockMvc.perform(request)
                .andExpect(status().is2xxSuccessful())
//                .andExpect(content().json(jsonResponse, true))
                .andExpect(jsonPath("$.id").value("2da4002a-31c5-4cc7-9b92-cbf0db998c41"))
//                .andExpect(jsonPath("$.title").value("category"))
                .andReturn();

        logger.info(mvcResult.getResponse().getContentAsString());
    }
    ...
}

Convert list of Objects to JSON Array in java - Spring Boot api testing

copy iconCopydownload iconDownload
[
  {
    "compania1_list": "Compania1 list",
    "name1": "name1",
    "s": "---",
    "s1": "---",
    "o": null,
    "o1": null
  },
  {
    "compania1_list": "Compania2 list",
    "name1": "name2",
    "s": "---",
    "s1": "---",
    "o": null,
    "o1": null
  }
]
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/lista")
public Map<String, Object> createCompanias(@RequestBody CompaniasCreationRequest companiasCreationRequest) {
    return companiaService.postListCompanias(companiasCreationRequest.getCompanias());
}
public class CompaniasCreationRequest {
    private List<Compania> companias;

    public CompaniasCreationRequest(List<Compania> companias) {
        this.companias = companias;
    }

    public List<Compania> getCompanias() {
        return companias;
    }

    public void setCompanias(List<Compania> companias) {
        this.companias = companias;
    }
}
@Test
void successSavePostCompaniaLista() throws Exception {
    Compania c1 = new Compania("Compania1 list",
        "name1",
        "---",
        "---",
        null,
        null);
    Compania c2 = new Compania("Compania2 list",
        "name2",
        "---",
        "---",
        null,
        null);

    CompaniasCreationRequest companiasCreationRequest = new CompaniasCreationRequest(List.of(c1,c2));
    
    when(companiaRepository.save(any(Compania.class))).then(returnsFirstArg());

    this.mockMvc.perform(
            post("/companias/lista")
                .header("authorization", "Bearer " + token)
                .content(asJsonString(companiasCreationRequest))
                .contentType(MediaType.APPLICATION_JSON))
        .andDo(print())
        .andExpect(status().isCreated())
        .andExpect(jsonPath("$.result[0].success[0]").isNotEmpty())
        .andExpect(jsonPath("$.result[0].success[0].name").value(c1.getName()))
        .andExpect(jsonPath("$.result[0].success[1].name").value(c2.getName()));
}
{
  "companias": [
    {
      "compania1_list": "Compania1 list",
      "name1": "name1",
      "s": "---",
      "s1": "---",
      "o": null,
      "o1": null
    },
    {
      "compania1_list": "Compania2 list",
      "name1": "name2",
      "s": "---",
      "s1": "---",
      "o": null,
      "o1": null
    }
  ]
}
-----------------------
[
  {
    "compania1_list": "Compania1 list",
    "name1": "name1",
    "s": "---",
    "s1": "---",
    "o": null,
    "o1": null
  },
  {
    "compania1_list": "Compania2 list",
    "name1": "name2",
    "s": "---",
    "s1": "---",
    "o": null,
    "o1": null
  }
]
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/lista")
public Map<String, Object> createCompanias(@RequestBody CompaniasCreationRequest companiasCreationRequest) {
    return companiaService.postListCompanias(companiasCreationRequest.getCompanias());
}
public class CompaniasCreationRequest {
    private List<Compania> companias;

    public CompaniasCreationRequest(List<Compania> companias) {
        this.companias = companias;
    }

    public List<Compania> getCompanias() {
        return companias;
    }

    public void setCompanias(List<Compania> companias) {
        this.companias = companias;
    }
}
@Test
void successSavePostCompaniaLista() throws Exception {
    Compania c1 = new Compania("Compania1 list",
        "name1",
        "---",
        "---",
        null,
        null);
    Compania c2 = new Compania("Compania2 list",
        "name2",
        "---",
        "---",
        null,
        null);

    CompaniasCreationRequest companiasCreationRequest = new CompaniasCreationRequest(List.of(c1,c2));
    
    when(companiaRepository.save(any(Compania.class))).then(returnsFirstArg());

    this.mockMvc.perform(
            post("/companias/lista")
                .header("authorization", "Bearer " + token)
                .content(asJsonString(companiasCreationRequest))
                .contentType(MediaType.APPLICATION_JSON))
        .andDo(print())
        .andExpect(status().isCreated())
        .andExpect(jsonPath("$.result[0].success[0]").isNotEmpty())
        .andExpect(jsonPath("$.result[0].success[0].name").value(c1.getName()))
        .andExpect(jsonPath("$.result[0].success[1].name").value(c2.getName()));
}
{
  "companias": [
    {
      "compania1_list": "Compania1 list",
      "name1": "name1",
      "s": "---",
      "s1": "---",
      "o": null,
      "o1": null
    },
    {
      "compania1_list": "Compania2 list",
      "name1": "name2",
      "s": "---",
      "s1": "---",
      "o": null,
      "o1": null
    }
  ]
}
-----------------------
[
  {
    "compania1_list": "Compania1 list",
    "name1": "name1",
    "s": "---",
    "s1": "---",
    "o": null,
    "o1": null
  },
  {
    "compania1_list": "Compania2 list",
    "name1": "name2",
    "s": "---",
    "s1": "---",
    "o": null,
    "o1": null
  }
]
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/lista")
public Map<String, Object> createCompanias(@RequestBody CompaniasCreationRequest companiasCreationRequest) {
    return companiaService.postListCompanias(companiasCreationRequest.getCompanias());
}
public class CompaniasCreationRequest {
    private List<Compania> companias;

    public CompaniasCreationRequest(List<Compania> companias) {
        this.companias = companias;
    }

    public List<Compania> getCompanias() {
        return companias;
    }

    public void setCompanias(List<Compania> companias) {
        this.companias = companias;
    }
}
@Test
void successSavePostCompaniaLista() throws Exception {
    Compania c1 = new Compania("Compania1 list",
        "name1",
        "---",
        "---",
        null,
        null);
    Compania c2 = new Compania("Compania2 list",
        "name2",
        "---",
        "---",
        null,
        null);

    CompaniasCreationRequest companiasCreationRequest = new CompaniasCreationRequest(List.of(c1,c2));
    
    when(companiaRepository.save(any(Compania.class))).then(returnsFirstArg());

    this.mockMvc.perform(
            post("/companias/lista")
                .header("authorization", "Bearer " + token)
                .content(asJsonString(companiasCreationRequest))
                .contentType(MediaType.APPLICATION_JSON))
        .andDo(print())
        .andExpect(status().isCreated())
        .andExpect(jsonPath("$.result[0].success[0]").isNotEmpty())
        .andExpect(jsonPath("$.result[0].success[0].name").value(c1.getName()))
        .andExpect(jsonPath("$.result[0].success[1].name").value(c2.getName()));
}
{
  "companias": [
    {
      "compania1_list": "Compania1 list",
      "name1": "name1",
      "s": "---",
      "s1": "---",
      "o": null,
      "o1": null
    },
    {
      "compania1_list": "Compania2 list",
      "name1": "name2",
      "s": "---",
      "s1": "---",
      "o": null,
      "o1": null
    }
  ]
}
-----------------------
[
  {
    "compania1_list": "Compania1 list",
    "name1": "name1",
    "s": "---",
    "s1": "---",
    "o": null,
    "o1": null
  },
  {
    "compania1_list": "Compania2 list",
    "name1": "name2",
    "s": "---",
    "s1": "---",
    "o": null,
    "o1": null
  }
]
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/lista")
public Map<String, Object> createCompanias(@RequestBody CompaniasCreationRequest companiasCreationRequest) {
    return companiaService.postListCompanias(companiasCreationRequest.getCompanias());
}
public class CompaniasCreationRequest {
    private List<Compania> companias;

    public CompaniasCreationRequest(List<Compania> companias) {
        this.companias = companias;
    }

    public List<Compania> getCompanias() {
        return companias;
    }

    public void setCompanias(List<Compania> companias) {
        this.companias = companias;
    }
}
@Test
void successSavePostCompaniaLista() throws Exception {
    Compania c1 = new Compania("Compania1 list",
        "name1",
        "---",
        "---",
        null,
        null);
    Compania c2 = new Compania("Compania2 list",
        "name2",
        "---",
        "---",
        null,
        null);

    CompaniasCreationRequest companiasCreationRequest = new CompaniasCreationRequest(List.of(c1,c2));
    
    when(companiaRepository.save(any(Compania.class))).then(returnsFirstArg());

    this.mockMvc.perform(
            post("/companias/lista")
                .header("authorization", "Bearer " + token)
                .content(asJsonString(companiasCreationRequest))
                .contentType(MediaType.APPLICATION_JSON))
        .andDo(print())
        .andExpect(status().isCreated())
        .andExpect(jsonPath("$.result[0].success[0]").isNotEmpty())
        .andExpect(jsonPath("$.result[0].success[0].name").value(c1.getName()))
        .andExpect(jsonPath("$.result[0].success[1].name").value(c2.getName()));
}
{
  "companias": [
    {
      "compania1_list": "Compania1 list",
      "name1": "name1",
      "s": "---",
      "s1": "---",
      "o": null,
      "o1": null
    },
    {
      "compania1_list": "Compania2 list",
      "name1": "name2",
      "s": "---",
      "s1": "---",
      "o": null,
      "o1": null
    }
  ]
}
-----------------------
[
  {
    "compania1_list": "Compania1 list",
    "name1": "name1",
    "s": "---",
    "s1": "---",
    "o": null,
    "o1": null
  },
  {
    "compania1_list": "Compania2 list",
    "name1": "name2",
    "s": "---",
    "s1": "---",
    "o": null,
    "o1": null
  }
]
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/lista")
public Map<String, Object> createCompanias(@RequestBody CompaniasCreationRequest companiasCreationRequest) {
    return companiaService.postListCompanias(companiasCreationRequest.getCompanias());
}
public class CompaniasCreationRequest {
    private List<Compania> companias;

    public CompaniasCreationRequest(List<Compania> companias) {
        this.companias = companias;
    }

    public List<Compania> getCompanias() {
        return companias;
    }

    public void setCompanias(List<Compania> companias) {
        this.companias = companias;
    }
}
@Test
void successSavePostCompaniaLista() throws Exception {
    Compania c1 = new Compania("Compania1 list",
        "name1",
        "---",
        "---",
        null,
        null);
    Compania c2 = new Compania("Compania2 list",
        "name2",
        "---",
        "---",
        null,
        null);

    CompaniasCreationRequest companiasCreationRequest = new CompaniasCreationRequest(List.of(c1,c2));
    
    when(companiaRepository.save(any(Compania.class))).then(returnsFirstArg());

    this.mockMvc.perform(
            post("/companias/lista")
                .header("authorization", "Bearer " + token)
                .content(asJsonString(companiasCreationRequest))
                .contentType(MediaType.APPLICATION_JSON))
        .andDo(print())
        .andExpect(status().isCreated())
        .andExpect(jsonPath("$.result[0].success[0]").isNotEmpty())
        .andExpect(jsonPath("$.result[0].success[0].name").value(c1.getName()))
        .andExpect(jsonPath("$.result[0].success[1].name").value(c2.getName()));
}
{
  "companias": [
    {
      "compania1_list": "Compania1 list",
      "name1": "name1",
      "s": "---",
      "s1": "---",
      "o": null,
      "o1": null
    },
    {
      "compania1_list": "Compania2 list",
      "name1": "name2",
      "s": "---",
      "s1": "---",
      "o": null,
      "o1": null
    }
  ]
}

how to test equality of data class with OffsetDateTime attribute?

copy iconCopydownload iconDownload
spring.jackson.deserialization.adjust-dates-to-context-time-zone=false
spring.jackson.time-zone=Europe/Berlin
-----------------------
spring.jackson.deserialization.adjust-dates-to-context-time-zone=false
spring.jackson.time-zone=Europe/Berlin

Community Discussions

Trending Discussions on JsonPath
  • delete the JSON object from one json object by comparing the id from another json object if id is not present in javascript/ node js
  • Any workaround for JSONPATH wildcard not supported in Spark SQL
  • Get pods in Kubernetes where all containers are &quot;ready&quot; in one line using kubectl
  • Unable to use jsonpath function for output parameter in Argo Workflows
  • Error Mapping Geometry type Point in PostgreSQL
  • Kubernetes CRD: Show durations in additionalPrinterColumns
  • Unable to authenticate service account - Google Cloud
  • How to mock JWT token to use it with Mockito and Spring Boot
  • Convert list of Objects to JSON Array in java - Spring Boot api testing
  • how to test equality of data class with OffsetDateTime attribute?
Trending Discussions on JsonPath

QUESTION

delete the JSON object from one json object by comparing the id from another json object if id is not present in javascript/ node js

Asked 2022-Mar-13 at 07:29

let data = getData();
let anotherObj = getAnotherObj();

let res = data.reduce((acc, curr) => {
  if (!acc[curr.system.name]) {
    acc[curr.system.name] = {};
  }

  let detailsObj = {};
  Object.keys(curr.DataDetails).forEach(key => {
    let values = curr.DataDetails[key];

    // special handling to flatten single attribute objects
    if (values.length === undefined || values.length === 0) {
      let keys = Object.keys(values);
      if (keys.length == 1 && typeof values[keys[0]] !== 'object') {
        detailsObj[key] = values[keys[0]];
        return;
      }
    }

    // clone values to output
    detailsObj[key] = !Array.isArray(values) ? Object.assign({}, values) : [...values];

    // find and replace ids
    let ids = jsonpath.query(detailsObj[key], '$..id');
    ids.forEach((id, i) => {
      if (id in anotherObj) {
        if (Array.isArray(detailsObj[key]))
          detailsObj[key].splice(i, 1, anotherObj[id]);
        else
          detailsObj[key] = anotherObj[id];
      }
    });
  });

  acc[curr.system.name][curr.system.id] = {
    title: curr.system.id,
    uid: curr.system.id,
    url: `/${curr.system.name}/${curr.system.id}`,
    ...detailsObj,
  };
  return acc;
}, {});

document.body.insertAdjacentHTML('beforeend', `<pre>${JSON.stringify(res, undefined, 1)}</pre>`);
console.log(res);



function getData() {
  return [{
      system: {
        id: "4gSSbjCFEorYXqrgDIP2FA",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        shortOption: {
          "en-us": "some value"
        },
        mediaFile: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "7kRzyt4PFo",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "2OspeCtNK0s",
            },
          },
        ],
        mediaGalary: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              linkType: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],
        
      },
    },
    {
      system: {
        id: "1aBOO8tu3lUsjtICuIbUM5",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        short: {
          "en-us": "details of shorts"
        },
        shortSlugOption: {
          "hi-In": "options"
        },
        booleanField: {
          kl: "true"
        },
      },
    },
    {
      system: {
        id: "2pOUGnI1oRD7nsrYs600HA",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: [{
            sys: {
              type: "Link",
              link: "Entry",
              id: "66rzYr2BpWL",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Entry",
              id: "1VTBHdLTdSW",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "66rzYr2BpWL1VTBHdLTdSW",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        oneReference: {
          sys: {
            type: "Link",
            linkType: "Asset",
            id: "h2cPiuU9jIz",
          },
        },
        multiReference: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "cIb5mqEBRWDD6hrNmFmFE",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        testingNewValue: {
          "hi-IN": "jksdsdo"
        }
      },
    },
    {
      system: {
        id: "7kRzyt4PFrX13gHcw3Z1Ko",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: {
          "en-us": "kknksdo"
        }
      },
    }
  ];
}


function getAnotherObj() {
  return {
    "h2cPiuU9jIz": {
      status: true,
      tag: [],
      filename: "wallpapers-6.jpg",
      is_dir: false,
      parent_uid: null,
    },
    
    
    "2OspeCtNK0s": {
      status: true,
      tag: [],
      filename: "mediaFile1.jpg",
      is_dir: false,
      parent_uid: null,
    },
    "66rzYr2BpWL": {
      type: 'entry',
      tag: [],
      entry_details: "this is first entry ***",
      is_secret: false,
    },
    "1VTBHdLTdSW": {
      type: 'entry',
      tag: [],
      entry_details: "some other entry ***",
      is_secret: true,
    },
  };
}
<script src="https://cdn.jsdelivr.net/npm/jsonpath@1.1.1/jsonpath.min.js"></script>

I am trying to put two object data in one output but by reading the link which is Asset

but in the multiple Array list the output is displaying as I want but the problem is while comparing the output from the anotherObj if the Id with that Obj is present it showing me the expected value which is data Asset replaced by the anotherObj

But I want to remove the value which is not matched with the object which are present inside the anotherObj

for eg:-

"mediaGalary": [
        {
          "sys": {
            "type": "Link",
            "link": "Asset",
            "id": "gHcw3Z1Ko"
          }
        },
        {
          /**id:c**/
          "status": true,
          "tag": [],
          "filename": "wallpapers-6.jpg",
          "is_dir": false,
          "parent_uid": null
        }
      ]

and

"mediaFile": [
    {
     "sys": {
      "type": "Link",
      "link": "Asset",
      "id": "7kRzyt4PFo"
     }
    },
    {
     "status": true,
     "tag": [],
     "filename": "mediaFile1.jpg",
     "is_dir": false,
     "parent_uid": null
    }
   ]

look like this here "id": "gHcw3Z1Ko" is not present inside the anotherObj so I want to remove all the object with that id

    {
     "sys": {
      "type": "Link",
      "link": "Asset",
      "id": "7kRzyt4PFo"
     }
    }

and

    {
     "sys": {
      "type": "Link",
      "link": "Asset",
      "id": "7kRzyt4PFo"
     }

as this id object is not present so I want to remove it and I wanted my expected output be like this it should only remove the Object which is not present inside the anotherObj

"mediaGalary": [
        {
          /**id:c**/
          "status": true,
          "tag": [],
          "filename": "wallpapers-6.jpg",
          "is_dir": false,
          "parent_uid": null
        }
      ]
and


"mediaFile": [
    {
     "status": true,
     "tag": [],
     "filename": "mediaFile1.jpg",
     "is_dir": false,
     "parent_uid": null
    }
   ]

ANSWER

Answered 2022-Mar-13 at 07:29

After we are done replacing items in data, whichever items remain with property id are not replaced, hence they are not in anotherObj.
So we can find them and remove them like this:

// find items with `id` proerty
let objs = jsonpath.nodes(acc, '$..[?(@.sys.id)]');

// delete the items
objs.forEach(function(node) {
  let key = node.path.pop();
  let parent = jsonpath.value(acc, jsonpath.stringify(node.path));
  if (Array.isArray(parent))
    parent.splice(key, 1);
  else
    delete parent[key];
}, this);

Demo:

let data = getData();
let anotherObj = getAnotherObj();

let res = data.reduce((acc, curr) => {
  if (!acc[curr.system.name]) {
    acc[curr.system.name] = {};
  }

  let detailsObj = {};
  Object.keys(curr.DataDetails).forEach(key => {
    let values = curr.DataDetails[key];

    // special handling to flatten single attribute objects
    if (values.length === undefined || values.length === 0) {
      let keys = Object.keys(values);
      if (keys.length == 1 && typeof values[keys[0]] !== 'object') {
        detailsObj[key] = values[keys[0]];
        return;
      }
    }

    // clone values to output
    detailsObj[key] = !Array.isArray(values) ? Object.assign({}, values) : [...values];

    // find and replace ids
    let ids = jsonpath.query(detailsObj[key], '$..id');
    ids.forEach((id, i) => {
      if (id in anotherObj) {
        if (Array.isArray(detailsObj[key]))
          detailsObj[key].splice(i, 1, anotherObj[id]);
        else
          detailsObj[key] = anotherObj[id];
      }
    });
  });

  acc[curr.system.name][curr.system.id] = {
    title: curr.system.id,
    uid: curr.system.id,
    url: `/${curr.system.name}/${curr.system.id}`,
    ...detailsObj,
  };

  // find items which were not replaced
  let objs = jsonpath.nodes(acc, '$..[?(@.sys.id)]');

  // delete the items
  objs.forEach(function(node) {
    let key = node.path.pop();
    let parent = jsonpath.value(acc, jsonpath.stringify(node.path));
    if (Array.isArray(parent))
      parent.splice(key, 1);
    else
      delete parent[key];
  }, this);

  return acc;
}, {});



document.body.insertAdjacentHTML('beforeend', `<pre>${JSON.stringify(res, undefined, 1)}</pre>`);
console.log(res);

function getData() {
  return [{
      system: {
        id: "4gSSbjCFEorYXqrgDIP2FA",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        shortOption: {
          "en-us": "some value"
        },
        mediaFile: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "7kRzyt4PFo",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "2OspeCtNK0s",
            },
          },
        ],
        mediaGalary: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              linkType: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],

      },
    },
    {
      system: {
        id: "1aBOO8tu3lUsjtICuIbUM5",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        short: {
          "en-us": "details of shorts"
        },
        shortSlugOption: {
          "hi-In": "options"
        },
        booleanField: {
          kl: "true"
        },
      },
    },
    {
      system: {
        id: "2pOUGnI1oRD7nsrYs600HA",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: [{
            sys: {
              type: "Link",
              link: "Entry",
              id: "66rzYr2BpWL",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Entry",
              id: "1VTBHdLTdSW",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "66rzYr2BpWL1VTBHdLTdSW",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        oneReference: {
          sys: {
            type: "Link",
            linkType: "Asset",
            id: "h2cPiuU9jIz",
          },
        },
        multiReference: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "cIb5mqEBRWDD6hrNmFmFE",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        testingNewValue: {
          "hi-IN": "jksdsdo"
        }
      },
    },
    {
      system: {
        id: "7kRzyt4PFrX13gHcw3Z1Ko",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: {
          "en-us": "kknksdo"
        }
      },
    }
  ];
}


function getAnotherObj() {
  return {
    "h2cPiuU9jIz": {
      status: true,
      tag: [],
      filename: "wallpapers-6.jpg",
      is_dir: false,
      parent_uid: null,
    },


    "2OspeCtNK0s": {
      status: true,
      tag: [],
      filename: "mediaFile1.jpg",
      is_dir: false,
      parent_uid: null,
    },
    "66rzYr2BpWL": {
      type: 'entry',
      tag: [],
      entry_details: "this is first entry ***",
      is_secret: false,
    },
    "1VTBHdLTdSW": {
      type: 'entry',
      tag: [],
      entry_details: "some other entry ***",
      is_secret: true,
    },
  };
}
<script src="https://cdn.jsdelivr.net/npm/jsonpath@1.1.1/jsonpath.min.js"></script>

Source https://stackoverflow.com/questions/70444724

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install JsonPath

You can download it from GitHub.
You can use JsonPath like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the JsonPath component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.