[英]How to use JSONPath (or any other option) to query an unnamed JSON array?
A REST API service provides the following JSON to my C# code: REST API服务为我的C#代码提供以下JSON:
[
{
"contentUri": "https://somewhere.com/aGuid1",
"contentId": "2"
},
{
"contentUri": "https://somewhere.com/aGuid2",
"contentId": "3"
},
{
"contentUri": "https://somewhere.com/aGuid3",
"contentId": "4"
}
]
Above JSON is simplified and the actual response is a VERY large string ,so is string manipulations will be costly and memory intensive. 以上JSON是简化的,实际响应是一个非常大的字符串,因此字符串操作将是昂贵的和内存密集型。
The problem is that the above JSON Array does not have a name. 问题是上面的JSON数组没有名称。 so I am not able to parse it into an JArray unless I manipulate the JSON string and add a name to it.
所以除非我操纵JSON字符串并为其添加名称,否则我无法将其解析为JArray。 I like to avoid that.
我想避免这种情况。
I can perfectly parse above JSON into a JToken. 我可以完美地将JSON解析为JToken。 Now I like to query within the JToken by using JToken.SelectToken and JSONPath
现在我喜欢使用JToken.SelectToken和JSONPath在JToken中进行查询
What JSONPath returns all of the elements in above JSON array? 什么JSONPath返回上面JSON数组中的所有元素?
What JSONPath returns all of the contentUri values in above JSON array? 什么JSONPath返回上面JSON数组中的所有contentUri值?
I've tried many JSONPath queries, but no lock since the array does not have a name. 我尝试了很多JSONPath查询,但没有锁,因为数组没有名称。
You can very easily parse the above json into a JArray
: 您可以非常轻松地将上面的json解析为
JArray
:
JArray array = JArray.Parse(jsonString);
To get all objects in the array, you don't need a JSONPath expression, just loop over the array: 要获取数组中的所有对象,您不需要JSONPath表达式,只需遍历数组:
foreach (JObject child in array)
{
Console.WriteLine("contentUri: " + (string)child["contentUri"]);
Console.WriteLine("contentId: " + (string)child["contentId"]);
}
For completeness, the equivalent JSONPath expression to get all the array values is [*]
. 为了完整性,获取所有数组值的等效JSONPath表达式为
[*]
。 But it doesn't really buy you anything here. 但它并没有真正给你买任何东西。
To get all the contentUri
values only, you can use SelectTokens
with the JSONPath [*].contentUri
: 要仅获取所有
contentUri
值,可以将SelectTokens
与JSONPath [*].contentUri
:
foreach (JToken uri in array.SelectTokens("[*].contentUri"))
{
Console.WriteLine(uri);
}
Alternatively, you could just Select
them like this: 或者,您可以像这样
Select
它们:
foreach (string uri in array.Select(t => (string)t["contentUri"]))
{
Console.WriteLine(uri);
}
Fiddle: https://dotnetfiddle.net/C2gIWX 小提琴: https : //dotnetfiddle.net/C2gIWX
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.