简体   繁体   English

格式 JSON 响应为 \

[英]format JSON response with \

I'm trying to format a json response as such:我正在尝试格式化 json 响应:

[
{
    "id": "23029",
    "label": "F:\path\to\file\filename.txt",
    "value": "filename.txt"
},
{
    "id": "23030",
    "label": "F:\path\to\file\filename.txt",
    "value": "filename.txt"
},
{
    "id": "23031",
    "label": "F:\path\to\file\filename.txt",
    "value": "filename.txt"
}

] ]

but according to JSONLint , the \ is breaking the "structure"?但根据JSONLint , \ 正在破坏“结构”? If I replace the \ with a |如果我用 | 替换 \ it works so I know the \ is the problem.它有效,所以我知道 \ 是问题所在。 I'm using the response in jQuery's Autocomplete .我正在使用jQuery 的自动完成中的响应。

Should I be using SerializeJSON() instead?我应该改用 SerializeJSON() 吗? If so, do I need to change something in the ajax autocomplete script?如果是这样,我是否需要更改 ajax 自动完成脚本中的某些内容?

$(function() {
    var cache = {},
        lastXhr;
    $( "#media" ).autocomplete({
        minLength: 2,
        source: function( request, response ) {
            var term = request.term;
            if ( term in cache ) {
                response( cache[ term ] );
                return;
            }

            lastXhr = $.getJSON( "ajax/search.cfm", request, function( data, status, xhr ) {
                cache[ term ] = data;
                if ( xhr === lastXhr ) {
                    response( data );
                }
            });
        }
    });
});

The \ is the escape character and needs to be escaped itself if it is part of the content. \是转义字符,如果它是内容的一部分,则需要自行转义。

So, the JSON string should like this before the client receives it:因此, JSON字符串在客户端收到之前应该是这样的:

[
    {
        "id": "23029",
        "label": "F:\\path\\to\\file\\filename.txt",
        "value": "filename.txt"
    },
    {
        "id": "23030",
        "label": "F:\\path\\to\\file\\filename.txt",
        "value": "filename.txt"
    },
    {
        "id": "23031",
        "label": "F:\\path\\to\\file\\filename.txt",
        "value": "filename.txt"
    }
]

have you tried to escape the backslash?你试过逃避反斜杠吗?

{
"id": "23030",
"label": "F:\\path\\to\\file\\filename.ext",
"value": "filename.txt"
}

While other responders have pointed out that you should be escaping the backslashes, if you were to use serializeJSON() it would take care of that escaping for you.虽然其他响应者指出反斜杠应该是 escaping,如果您要使用 serializeJSON(),它会为您处理 escaping。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM