是否可以使用 JsonPath 从 json 中提取串联值

问题描述 投票:0回答:1

是否可以使用 JSONPath 从 JSON 中提取串联值?我想从 JSON 数组属性获取地址作为完整的地址列表。

这是我的 JSON 输入。看起来像

{"quoteSummary": {"result": [{"address": "One Apple Park Way","city": "Cupertino"},{"address": "Microsoft","city": "New York"}]}}

如果我运行下面的代码

var jsonString = @"{ ""quoteSummary"": { ""result"": [ { ""address1"": ""One Apple Park Way"", ""city"": ""Cupertino"" }, { ""address1"": ""Microsoft"", ""city"": ""New York"" } ] } }";
var data = (JObject)JsonConvert.DeserializeObject(jsonString);
var SelectStrings = data.SelectTokens("quoteSummary.result..['address1','city']");

我收到的输出为

["One Apple Park Way", "Cupertino", "Microsoft", "New York"]

但是我想要

["One Apple Park Way , Cupertino", "Microsoft , New York"]

注意:此 JSON 路径在 Json Path Evaluator 中不起作用,但可以在 Visual Studio 中使用。

我尝试使用(地址&''&城市)

c# json .net json.net jsonpath
1个回答
0
投票

Json.NET 的 JSONPath 实现不支持

Concat()
运算符。您可以在源代码中检查
QueryOperator
枚举
以获取所有支持的运算符;没有任何东西类似于
Concat()
[1]

相反,您可以将 JSONPath 查询与 LINQ

Select()
投影结合起来,如下所示:

var selectStrings = data
    .SelectTokens("quoteSummary.result[*]") // Select all quoteSummary.result objects
    .Select(o => string.Join(" , ", o["address1"], o["city"])) // And join the address1 and city properties of each into a string
    .ToList(); // And materialize into a list of strings.

这会导致

["One Apple Park Way , Cupertino","Microsoft , New York"]

演示小提琴在这里


[1] 在发表此答案时,13.0.3 是最新发布的 Json.NET 版本。它支持以下运算符

internal enum QueryOperator
{
    None = 0,
    Equals = 1,
    NotEquals = 2,
    Exists = 3,
    LessThan = 4,
    LessThanOrEquals = 5,
    GreaterThan = 6,
    GreaterThanOrEquals = 7,
    And = 8,
    Or = 9,
    RegexEquals = 10,
    StrictEquals = 11,
    StrictNotEquals = 12
}

如您所见,没有

Concat()

© www.soinside.com 2019 - 2024. All rights reserved.