gpt4 book ai didi

c# - 从给定的 JSON 文件中检索特定属性

转载 作者:行者123 更新时间:2023-11-30 17:25:43 26 4
gpt4 key购买 nike

我正在尝试使用 JSONPath 表达式查询一个 JSON 文件,使用JObject.selectTonkens() 调用。不幸的是,我没有得到预期的输出。

我试过很多方法 https://jsonpath.com/以及 Newtonsoft。

这些是没有给我预期结果的几次尝试:

IEnumerable<JToken> rawProperties = obj.SelectTokens("$.properties[?(@..type)]");
foreach (JToken token in rawProperties)
{
Console.WriteLine(token);
}

这确实为我提供了具有类型的每个属性(包括我不想要的属性)。我已经在 visual studio 中试过了。

最佳尝试:

$.properties[?(@.type != 'array')]

我已经在 https://jsonpath.com/ 上试过了, 不幸的是,它在 Visual Studio 上根本不起作用。它给了我很好的预期结果,但没有我需要的键(参见我帖子末尾的预期输出):

[
{
"type": "string",
"description": "Identifiant technique de l'action de régulation."
},
{
"type": "string",
"description": "Description de l'action de régulation."
},
{
"type": "string",
"description": "situations/id : identifiant technique de la situation."
}
]

这是我要查询的 JSON 文件的示例:

{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "actionRegulation",
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Identifiant technique de l'action de régulation."
},
"description": {
"type": "string",
"description": "Description de l'action de régulation."
},
"idSituation": {
"type": "string",
"description": "situations/id : identifiant technique de la situation."
},
"pointsJalonnement": {
"type": "array",
"items": {
"title": "PointJalonnement",
"type": "object",
"properties": {
"rang": {
"type": "integer",
"description": "Rang du point de jalonnement."
},
"refJalon": {
"type": "string",
"description": "Référence du point de jalonnement (PR/CR-CI-CH)."
},
"typeModification": {
"type": "string",
"description": "Renseigné que si modification d'horaire (utile à IENA)."
}
}
}
}
}
}

我想检索所有属性(包括它们的名称,如“id”、“description”)但不是“type”:“array”并且不属于“array”类型对象,即也就是说是内在属性。例如,我不想从我的查询“refJalon”、“typeModification”等中检索。所以我希望从我的查询中得到以下结果:

[
"id":
{
"type": "string",
"description": "Identifiant technique de l'action de régulation."
},
"description":
{
"type": "string",
"description": "Description de l'action de régulation."
},
"idSituation":
{
"type": "string",
"description": "situations/id : identifiant technique de la situation."
}
]

任何帮助都将不胜感激:我应该使用的其他技术/框架、一些特定的文档等。谢谢!

最佳答案

使用JsonPath可能得不到你想要的结果; @dbc 在评论中提到了一些限制。但是,您可以使用非常简单的 LINQ-to-JSON 查询获得所需的结果:

IEnumerable<JToken> rawProperties = obj["properties"]
.Children<JProperty>()
.Where(jp => (string)jp.Value["type"] != "array");

foreach (JToken token in rawProperties)
{
Console.WriteLine(token);
}

fiddle :https://dotnetfiddle.net/A4ZbEG

关于c# - 从给定的 JSON 文件中检索特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57902355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com