gpt4 book ai didi

javascript - 如何提取这个json?

转载 作者:行者123 更新时间:2023-11-29 18:31:25 25 4
gpt4 key购买 nike

我有这样的结果

{
"Errors" : {
"Failure" : {
"ShowAsPopup" : true,
"ErrorMessage" :"Some Message.",
"PopupTitle" : null
}
},
"IsValid" : false,
"WarningMessage" : null,
"SuccessMessage" : null
}

现在,如果我执行 Errors.Failure.ShowAsPopup,我会得到一个值。什么是预期的。但是我想改用索引(如果可能的话)

我试过了

Errors[0].Failure.ShowAsPopup 但这只是给我未定义的。理想情况下,我希望它像 Errors[0].[0].ShowAsPopup 这样我不必指定“失败”,但我可能不得不重新考虑那部分。

我想要一种通用的方法来处理我的错误。看到一些错误需要弹出窗口,有些只是验证错误。所以现在我把它们都硬编码了,我正试图摆脱它。我宁愿只检查该错​​误是否需要弹出窗口。

所以代替

if(response.Errors.Failure) { // alert('hi')};
else if(response.Errors.Failure2 {// alert('hi2')}

等等 我只需要一个可以进行检查的 if 语句。

最佳答案

您的代码和数据必须匹配。如果数据是这样的:

{"Errors":{"Failure":{"ShowAsPopup":true,"ErrorMessage":"Some Message.","PopupTitle":null}},"IsValid":false,"WarningMessage":null,"SuccessMessage":null}

多行形式看起来像这样:

var data = {
"Errors": {
"Failure": {
"ShowAsPopup":true,
"ErrorMessage":"Some Message.",
"PopupTitle":null
}
},
"IsValid":false,
"WarningMessage":null,
"SuccessMessage":null
}

然后,您必须使用代码来匹配您的数据,在本例中为 Errors.Failure.ShowAsPopup。由于数据是对象形式,您必须使用对象语法来读取它。数组和对象不可互换。如果要使用Array语法读取数据,那么数据就需要在不同的版面上。

您可以像这样编写一个通用错误函数:

if (!data.IsValid) {
handleError(data);
}

function handleError(info) {
if (info.Errors ) {
if (info.Errors.Failure) {
if (info.Errors.Failure.ShowAsPopup) {
// show a popup error here using info.Errors.Failure.ErrorMessage
}
} else if (/* other types of errors here */) {
// handle other types of errors here
}
}
}

关于javascript - 如何提取这个json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7800655/

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