什么是JavaScript库或者模块,可以更新基于jsonpath JSON?
我已经使用了一些Java库之前实现这一目标。我想既然JSON是更内在的JavaScript到Java,它应该是很容易发现,确实是一个图书馆。但令人意外的没有。
给定一个JSON对象:什么,我找是一个例子:
{
"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
}
}
}
和Jsonpath喜欢:
'$..author'
我可以调用一个JavaScript函数,它的JSONObject,JsonPath和NEWVALUE(莎士比亚)作为输入参数,并且JSONPATH的所有出现的值改变为一个新的值,例如至
{
"store": {
"book": [
{
"category": "reference",
"author": "Shakespeare",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Shakespeare",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Shakespeare",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "Shakespeare",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
有什么建议么?
回答如下:尝试使用jsonpath NPM包。
使用适用方法来改变JSON对象的值并返回节点。你需要添加一些方法,将根据每个节点的路径来更改值。
const _ = require('lodash');
var jp = require('jsonpath');
const data = {
"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
}
}
}
var nodes = jp.apply(data, '$..author', function(value) { return value.toUpperCase() });
// [
// { path: ['$', 'store', 'book', 0], value: 'NIGEL REES' },
// { path: ['$', 'store', 'book', 1], value: 'EVELYN WAUGH' },
// { path: ['$', 'store', 'book', 2], value: 'HERMAN MELVILLE' },
// { path: ['$', 'store', 'book', 3], value: 'J. R. R. TOLKIEN' }
// ]
function chnageValueByPath(object, path, value) {
if(Array.isArray(path) && path[0] === '$') {
const pathWithoutFirstElement = path.slice(1);
_.set(object, pathWithoutFirstElement, value);
}
}
function changeValuesByPath(object, nodes, lastPropertyName) {
nodes.forEach((node)=> {
chnageValueByPath(object, node.path.concat(lastPropertyName), node.value);
})
return object;
}
const result = changeValuesByPath(data, nodes, 'author');
console.log(result);