举个例子
{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
}
从
$.phoneNumbers[0].type
我可以解析["iPhone"]
但我只想要 iPhone
作为字符串值。如果我尝试$.phoneNumbers[0].type[0]
它返回i
。如果我在 js 中使用像 result[0]
这样的结果,它会返回 [
。在这一点上,我不知道该怎么做,欢迎任何帮助。我真的很陌生。
[0]
而不是[:1]
JSONpath,由于某种原因,总是在屏幕显示上输出一个对象或数组。
当你在 Javascript 中实际使用这个语法时,你会得到一个普通的字符串,
"iPhone"
,而不是一个数组["iPhone"]
.
这是你得到的比较:
const $ = {
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
}
console.log($.phoneNumbers[0].type)
如果你想使用表达式 $.phoneNumbers[:1].type 从 JSON 中提取字符串值“iPhone”,你可以在 JavaScript 中使用以下方法:
const jsonString =
'{"firstName":"John","lastName":"doe","age":26,"address":{"streetAddress":"naist street","city":"Nara","postalCode":"630-0192"},"phoneNumbers":[{"type":"iPhone","number":"0123-4567-8888"},{"type":"home","number":"0123-4567-8910"}]}';
const jsonObject = JSON.parse(jsonString);
const phoneType = jsonObject.phoneNumbers[0].type;
console.log(phoneType); // outputs "iPhone"