jsonpath.get 用于从 JSON 字符串中获取对应路径的值。
get(json: string, path: string): string | number | boolean | object
参数
参数 | 类型 | 描述 |
json | string | JSON 字符串 |
path | string | 取值路径 |
返回
类型 | 描述 |
string、number、boolean 或 object | 取值得到的数据 |
样例
获取给定路径的值:
import jsonpath from 'pts/jsonpath';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(jsonpath.get(json, 'name.last')); // Andersonconsole.log(jsonpath.get(json, 'age')); // 37console.log(jsonpath.get(json, 'children')); // Sara,Alex,Jackconsole.log(jsonpath.get(json, 'children[*]')); // Sara,Alex,Jackconsole.log(jsonpath.get(json, 'children.[0]')); // Saraconsole.log(jsonpath.get(json, 'children[1:2]')); // Alex,Jackconsole.log(jsonpath.get(json, 'friends[:].first')); // Dale,Roger,Janeconsole.log(jsonpath.get(json, 'friends[1].last')); // Craigconsole.log(jsonpath.get(json, 'friends[?(@.age > 45)].last')); // Craig,Murphyconsole.log(jsonpath.get(json, 'friends[?(@.first =~ /D.*e/)].last')); // Murphy}