JSON to JSON transformer

2020-01-27 03:09发布

I got a scenario.

Required input and output are JSON.

// Input
{
  "OldObject": {
    "Time": 1351160457922,
    "Name": "OName",
    "quantity": 100,
    "price": 10
  }
}


// Output
{
  "NewObject": {
    "Time": 1351160457922,
    "Title": "OName",
    "quantity": 100
  }
}

I need some transformation code or preferably xslt type language to transform json from one format to another. This transformer also need to be fast as transformation will be done on the fly.

Edit
I don't have the definition of the INPUT object received and it might change at run time. but I can use class for OUTPUT object if needed. I have tried to do this as json -> xml -> xslt -> xml -> json, but approximately 1000 objects are received per second at this end and this process might incur overhead.
I can not also use JavaScript as myApp is simple windows based java application and using JavaScript might cause overhead.

7条回答
冷血范
3楼-- · 2020-01-27 03:39

You can do this transformation with JSON patch.

Example with jsonpatch-js:

var transformations = [
  { move: '/OldObject', to: '/NewObject' },
  { remove: '/NewObject/price' },
  { move: '/NewObject/Name', to: '/NewObject/Title' }
];

var oldObject = { "OldObject": { "Time": 1351160457922, "Name": "OName", "quantity": 100, "price": 10 } };

jsonpatch.apply(oldObject, transformations);

I did not test the provided, but should work like that.

There are Java implementations for JSON patch:

查看更多
做个烂人
4楼-- · 2020-01-27 03:41

You can use ZORBA and JsonIQ http://www.jsoniq.org/ However, it's a native library, it comes with a wrapper so you can use it in java.

查看更多
时光不老,我们不散
5楼-- · 2020-01-27 03:43

Try JOLT. It is a JSON to JSON transformation library written in Java. It was created on a project that was transforming lot of JSON from an ElasticSearch "backend" to a frontend api.

For the JSON transform you have listed in your problem, the Jolt "shift" spec would be :

// Jolt "shift" spec
{
    "OldObject": {
        "Time": "NewObject.Time",   
        "Name": "NewObject.Title", // if the input has "OldObject.Name", copy it's value
                                   // to "NewObject.Title
        "quantity": "NewObject.quantity"
    }
}
查看更多
萌系小妹纸
6楼-- · 2020-01-27 03:44

Another option is use Logz.io Sawmill library. You define a pipeline and execute it. For you example:

{
  steps: [
    {
      rename {
         config {
            from: "OldObject"
            to: "NewObject"
         }
      }
    }

    {
      removeField {
        config {
          path: "NewObject.price"
        }
      }
    }

    {
      rename {
        config {
          from: "NewObject.Name"
          to: "NewObject.Title"
        }
      }
    }
  ]
}
查看更多
We Are One
7楼-- · 2020-01-27 03:45

You can try Java library Silencio that allows you to convert each node of the JSON file into new values. You can decide which and how nodes should be transformed.

查看更多
登录 后发表回答