gpt4 book ai didi

javascript - 在 jQuery 调用中编码 json

转载 作者:行者123 更新时间:2023-11-29 19:29:12 24 4
gpt4 key购买 nike

我有一个这样的 json :

{
"One\-test": {
"name" : "One\-test",
"link" : "xxx"
},
"Two\-test": {
"name" : "Two\-test",
"link" : "yyy"
}
}

在我的 javascript 文件中,我使用了 jQuery 调用

var myJson;
jQuery.getJSON('path/myJson.json', function (data) {
myJson = data;
});

不幸的是,调用没有成功,因为 myJson = data 没有被执行(我试图在语句之前放置一条控制台消息,但它没有被执行)和变量 myJson 仍未定义(我用 $.when 语句等待调用结束,然后打印出 myJson)。问题很可能是名称 One\-testTwo\-test 的格式(字符 '\' 和 '-' ),因为路径是正确的 (我相当确定)。我无法更改这些名称,然后我必须考虑其他事情。任何想法?我试过这样的 ajax 调用:

function getJson(myJson){
$.ajax({
type: "GET",
url: "path/myJson.json",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function(data) {
myJson = data;
}
});
}

但结果还是一样。

编辑

如果我尝试用 :

执行相同的代码
  {
"Onetest": {
"name" : "One\-test",
"link" : "xxx"
},
"Twotest": {
"name" : "Two\-test",
"link" : "yyy"
}
}

它成功了。这是“格式错误”的另一个证明

最佳答案

If I try to execute the same code with :

...

it succeed. This is another proof of "bad format"

好的,这告诉我们正在使用的 JSON 解析器正在将那些 "One\-test" 字符串解释为无效。你可以阅读 http://json.org那样(看起来 http://jsonlint.com 的人会这样做,因为它也拒绝这些字符串),虽然 the RFC says

Any character may be escaped.

...认为虽然毫无意义,但 - 之前的 \ 不应该是一个错误。但也许 RFC 意味着任何字符都可以作为 Unicode 转义或类似字符进行转义。

最好的事情就是你说你不能做的事情:修复 JSON,删除之前的 at-best-unnecessary-at-worst-problematic \ -

下一个最好的事情是做一些预处理。您可以通过告诉 jQuery 尝试解析 JSON 来直接替换字符串:

$.ajax({
type: "GET",
url: "path/myJson.json",
data: {},
dataType: "text", // <=== Don't parse it
success: function(data) {
// ...
}
});

然后在 success 做:

myJson = JSON.parse(data.replace(/\\-/g, "-"));

...当然,这是一个非常幼稚的替代品。

这是第二部分的演示:

var data =
'{' +
'"One\-test": {' +
' "name" : "One\-test",' +
' "link" : "xxx" ' +
' },' +
'"Two\-test": {' +
' "name" : "Two\-test",' +
' "link" : "yyy" ' +
' }' +
'}';
var myJson = JSON.parse(data.replace(/\\-/g, "-"));
snippet.log(myJson["One-test"].name); // "One-test"
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

关于javascript - 在 jQuery 调用中编码 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29076864/

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