Const
从 json 字符串中取值。
import gjson from 'pts/gjson';
export default function () {
const json = JSON.stringify({
"name": {"first": "Tom", "last": "Anderson"},
"age": 37,
"children": ["Sara", "Alex", "Jack"],
"fav.movie": "Deer Hunter",
"friends": [
{"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},
{"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]},
{"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]}
]
});
console.log(gjson.get(json, 'name.last')); // Anderson
console.log(gjson.get(json, 'age')); // 37
console.log(gjson.get(json, 'children')); // Sara,Alex,Jack
console.log(gjson.get(json, 'children.#')); // 3
console.log(gjson.get(json, 'children.1')); // Alex
console.log(gjson.get(json, 'child*.2')); // Jack
console.log(gjson.get(json, 'c?ildren.0')); // Sara
console.log(gjson.get(json, 'fav\\.movie')); // Deer Hunter
console.log(gjson.get(json, 'friends.#.first')); // Dale,Roger,Jane
console.log(gjson.get(json, 'friends.1.last')); // Craig
console.log(gjson.get(json, 'friends.#(last=="Murphy").first')); // Dale
console.log(gjson.get(json, 'friends.#(last=="Murphy")#.first')); // Dale,Jane
console.log(gjson.get(json, 'friends.#(age>45)#.last')); // Craig,Murphy
console.log(gjson.get(json, 'friends.#(first%"D*").last')); // Murphy
console.log(gjson.get(json, 'friends.#(first!%"D*").last')); // Craig
console.log(gjson.get(json, 'friends.#(nets.#(=="fb"))#.first')); // Dale,Roger
};
json 字符串
取值路径
取值数据
修改 json 字符串。
import gjson from 'pts/gjson';
export default function () {
// Set a value from empty document:
console.log(gjson.set('', 'name', 'Tom'));
// {"name":"Tom"}
// Set a nested value from empty document:
console.log(gjson.set('', 'name.last', 'Anderson'));
// {"name":{"last":"Anderson"}}
// Set a new value:
console.log(gjson.set(`{"name":{"last":"Anderson"}}`, 'name.first', 'Sara'));
// {"name":{"last":"Anderson","first":"Sara"}}
// Update an existing value:
console.log(gjson.set(`{"name":{"last":"Anderson"}}`, 'name.last', 'Smith'));
// {"name":{"last":"Smith"}}
// Set a new array value:
console.log(gjson.set(`{"friends":["Andy","Carol"]}`, 'friends.2', 'Sara'));
// {"friends":["Andy","Carol","Sara"]}
// Append an array value by using the -1 key in a path:
console.log(gjson.set(`{"friends":["Andy","Carol"]}`, 'friends.-1', 'Sara'));
// {"friends":["Andy","Carol","Sara"]}
// Append an array value that is past the end:
console.log(gjson.set(`{"friends":["Andy","Carol"]}`, 'friends.4', 'Sara'));
// {"friends":["Andy","Carol",null,null,"Sara"]}
};
json 字符串
修改路径
修改值
json 字符串
从 json 字符串中删除值。