gpt4 book ai didi

javascript - 如何通过 super 嵌套Json中的键获取值

转载 作者:行者123 更新时间:2023-11-30 19:14:55 25 4
gpt4 key购买 nike

"_embedded": {
"cscaia:status_report": {
"_links": {
"self": {
"title": "status_report",
"name": "status_report",
"href": "https://api.dxc-dev-aia.hub-1.dev.us.insurance.dxc.com/quotes/ID-mrMxY1Dg/status_report"
},
"type": {
"href": "https://diaas-dev.gtaia-test-domain.net/std-dev-lux-13100/insurance/schemas/quotes/statusReportDocument"
},
"up": {
"href": "https://api.dxc-dev-aia.hub-1.dev.us.insurance.dxc.com/quotes/ID-mrMxY1Dg"
}
},
"consistent": false,
"messages": [
{
"message": "Incomplete attribute",
"context": [
{
"propertyNames": [
"quote$distributor_id"
]
}
],
"severity": "error",
"code": "incomplete_attr"
}
]
}

在这里,我需要找出键“严重性”的值,但我不知道它的级别。我也没有它的父项的键,它嵌套在其中,因为 json 将始终充满活力。

我试过扩展方法。但是对于嵌套键,我没有得到结果。

public static TType JsonValue<TType>(this JObject obj, string key)
{
object result = null; //default to null if nothing is found

foreach (var item in obj)
{
var token = item;

if (token.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase))
{
result = token.Value.ToObject<TType>(); //return the value found
break;
}

if (!obj[token.Key].Children().Any())
continue;

var jt = obj[token.Key].ToString();

if (!jt.StartsWith("["))
{
result = JsonValue<TType>(JObject.Parse(jt), key);
}
else
{
obj[token.Key].Children().ToList().ForEach(x =>
{
//only the first match will be returned
result = JsonValue<TType>(JObject.Parse(x.ToString()), key);
});
}

if (result != null)
break;
}
return (TType)result;
}

最佳答案

您可以采用递归方法并在找到值时返回。

function getValue(object, key) {
var value;

if (!object || typeof object !== 'object') return;
if (key in object) return object[key];

Object.values(object).some(v => {
value = getValue(v, key)
return value !== undefined;
});

return value;
}

var data = { _embedded: { "cscaia:status_report": { _links: { self: { title: "status_report", name: "status_report", href: "https://api.dxc-dev-aia.hub-1.dev.us.insurance.dxc.com/quotes/ID-mrMxY1Dg/status_report" }, type: { href: "https://diaas-dev.gtaia-test-domain.net/std-dev-lux-13100/insurance/schemas/quotes/statusReportDocument" }, up: { href: "https://api.dxc-dev-aia.hub-1.dev.us.insurance.dxc.com/quotes/ID-mrMxY1Dg" } }, consistent: false, messages: [{ message: "Incomplete attribute", context: [{ propertyNames: ["quote$distributor_id"] }], severity: "error", code: "incomplete_attr" }] } } };

console.log(getValue(data, 'severity'));
console.log(getValue(data, 'href'));

关于javascript - 如何通过 super 嵌套Json中的键获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58098991/

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