简体   繁体   中英

format JSON response with \

I'm trying to format a json response as such:

[
{
    "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"? If I replace the \ with a | it works so I know the \ is the problem. I'm using the response in jQuery's Autocomplete .

Should I be using SerializeJSON() instead? If so, do I need to change something in the ajax autocomplete script?

$(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:

[
    {
        "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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