使用JSONPath从JSON对象获取单个值 [英] Getting a single value from a JSON object using JSONPath
问题描述
我有以下JSON,我需要使用 JSONPath 来获取普通的name
值:
I have the following JSON and I need to get the plain name
value using JSONPath:
{
"single" : {
"id" : 1,
"name" : "Item name"
}
}
我使用的表达式是$.single.name
,但我总是得到一个数组:
Expression that I used is $.single.name
but I always get an array:
[ "Item name" ]
代替字符串值("Item name"
).
推荐答案
但是我总是得到一个数组:
那是必然的.您可以在此文档的结果"(几乎在底部)下阅读:
That is meant to happen. As you can read in this documentation, under 'Result' (almost at the bottom):
请注意,jsonPath的返回值是一个数组,即 也是有效的JSON结构.因此,您可能需要将jsonPath应用到 再次得到结果结构,或使用您喜欢的数组之一 方法.
Please note, that the return value of jsonPath is an array, which is also a valid JSON structure. So you might want to apply jsonPath to the resulting structure again or use one of your favorite array methods as sort with it.
因此,基本上它将始终返回一个数组.如果您需要其他类型的数据,例如在这种情况下,如果使用字符串,恐怕您必须自己进行转换.
So basically it will always return an array. If you need the data as an other type, e.g. a String in this case, you will have to do the conversion yourself I'm afraid.
这篇关于使用JSONPath从JSON对象获取单个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!