使用JPATH,如何在另一个JSON字符串中选择JSON值?

时间:2020-12-01 07:08:30

I have the following JSON (simplified / minimized to show only pertinent parts) returned from a web service:

我从Web服务返回以下JSON(简化/最小化以仅显示相关部分):

{
    "results": [{
        "paramName": "OutputPolyline",
        "dataType": "String",
        "value": "#{\"hasM\":true,\"paths\":[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]}"
    }],
    "messages": []
}

I use the following code to parse the JSON and grab the value of the "value" key:

我使用以下代码来解析JSON并获取“value”键的值:

JObject obj = JObject.Parse(json);
JToken token = obj.SelectToken("$.results[?(@.paramName == 'OutputPolyline')]['value']");

Console.WriteLine(token.Path + " -> " + token);

The above code returns the entire value string as expected, like such "#{\"hasM\":true,\"paths\":[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]}"

上面的代码按预期返回整个值字符串,如“#{\”hasM \“:true,\”paths \“:[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,空]]]}”

Building on the above code, how do I get only the value of the paths key? In this example, return only [[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]

基于上面的代码,我如何只获取路径键的值?在此示例中,仅返回[[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]

1 个解决方案

#1


1  

You cannot extract the path values from the root object via a single JsonPath query since the value of the value property is just a string literal that happens itself to be re-serialized JSON. It needs to be extracted and recursively parsed as JSON after first trimming off the # character, and Json.NET has no built-in query operator to do that as of the current version, 9.0.1.

您无法通过单个JsonPath查询从根对象中提取路径值,因为value属性的值只是一个字符串文字,它本身就是重新序列化的JSON。在首次修剪#字符后,需要将其提取并递归解析为JSON,而Json.NET在当前版本9.0.1中没有内置查询运算符。

Thus you need to do something like:

因此,您需要执行以下操作:

JToken token = obj.SelectToken("$.results[?(@.paramName == 'OutputPolyline')]['value']");

var paths = JToken.Parse(token.ToString().Trim('#')).SelectToken("paths");

Sample fiddle.

#1


1  

You cannot extract the path values from the root object via a single JsonPath query since the value of the value property is just a string literal that happens itself to be re-serialized JSON. It needs to be extracted and recursively parsed as JSON after first trimming off the # character, and Json.NET has no built-in query operator to do that as of the current version, 9.0.1.

您无法通过单个JsonPath查询从根对象中提取路径值,因为value属性的值只是一个字符串文字,它本身就是重新序列化的JSON。在首次修剪#字符后,需要将其提取并递归解析为JSON,而Json.NET在当前版本9.0.1中没有内置查询运算符。

Thus you need to do something like:

因此,您需要执行以下操作:

JToken token = obj.SelectToken("$.results[?(@.paramName == 'OutputPolyline')]['value']");

var paths = JToken.Parse(token.ToString().Trim('#')).SelectToken("paths");

Sample fiddle.