简体   繁体   中英

Java create a new Json reading from another Json using jsonpath

In java (any library), starting from a json like the following (with nested fields, arrays and embedded documents):

{
  "first" : "1",
  "second" : {
     "third" : "3",
     "fourth" : "4"
  },
  "fifth" : [
     {
        "index" : 0,
        "value": "something"
     },
     {
        "index" : 1,
        "value": "else"
     }
  ]
}

and then apply following jsonpaths (as example, ideally any kind of jsonpath)

  • second.fourth
  • fifth[1].[*]

create a json document like the following:

{
  "second" : {
    "fourth" : "4"
  },
  "fifth" : [
     {
        "index" : 1,
        "value": "else"
     }
  ]
}

So the question is: it's possible to use jsonpath not only to get data but also all nested fields and create a new json as subset of input?

Any example is appreciated like always

Note : after thinking a lot about this, I've come to conclusion that what I need is an implementation of $project from Mongodb, but in Java and without a database.

If you can use lodash, there is set and get function for objects.

var source = {
  "first" : "1",
  "second" : {
     "third" : "3",
     "fourth" : "4"
  },
  "fifth" : [
     {
        "index" : 0,
        "value": "something"
     },
     {
        "index" : 1,
        "value": "else"
     }
  ]
};

var destination = {};

var path = "second.fourth";

_.set(destination, path, _.get(source, path));

path = "fifth[0]";     //Drawback -> if use fifth[1], then destination.fifth will have 0th element empty and 1st element filled.

_.set(destination, path, _.get(source, path));

Else you will need to write the javascript for these set and get operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM