简体   繁体   中英

How to escape double quotes between JS and JSON

I'm trying to construct a String in JS that can be passed into JSON as an with a very particular format. Desired result is a string of the following form:

["PNG","350x150","127 KB"]

Where PNG correspond to a particular image's type, where 350x150 is the image's dimensions and where 127 KB is the image's size. Each of these threee values are string variables:

var imgType = getImageType(); // Returns "PNG"
var imgDim = getImageDim(); // Returns "350x150"
var imgSize = getImageSize(); // Returns "127 KB"

var imgDescription = '["' + imgType + '","' + imgDim + '","' + imgSize + '"]';

// Sanity check
alert(imgDescription);

iVO.images[thisImage] = {
    "fizz":"buzz",
    "imgDesc":imgDescription,
    "foo":"bar"
}

alert(JSON.stringify(iVO));

The first alert (on the imgDescription variable) prints:

["PNG","350x150","127 KB"]

So far, so good. However, the minute we pass it to the iVO construct and stringify the resultant JSON, it generates the following output (after I pretty print format it):

{
    "images":
    {
        "4490i45"":
        {
            "fizz":"buzz",
            "imgDesc":"[\"PNG\",\"350x150\",\"127 KB\"]",
            "foo":"bar"
        }
    }
}

All of my double quotes (") have been escaped (\\")!!! Also, the value for imgDesc is enclosed in double-quotes, which is not what we want (see desired JSON below):

When I send this JSON back to the server its causing the server to choke.

Not sure what is going on here but I've tried several other suggestions, including replacing my double-quotes with '\\x22' instances which didn't help.

Any ideas as to what would fix this to get the desired result from JSON.stringify(iVO) ? Ultimately that's the only thing that matters, that the we end up sending the following to the server:

{
    "images":
    {
        "4490i45"":
        {
            "fizz":"buzz",
            "imgDesc":["PNG","350x150","127 KB"],
            "foo":"bar"
        }
    }
}

No escaped double-quotes, and the value for imgDesc is not double-quoted. Thanks in advance!

Why don't you just put imgDescription as regular array

var imgDescription = [imgType , imgDim, imgSize];

Stringify should take care of what you are trying to do, otherwise you are passing imgDescription as a string and stringify would escape the quotes.

eg

var imgType = "PNG";
var imgDim = "350x150";
var imgSize = "127 KB";
var d = {
    "fizz":"buzz",
    "imgDesc":[imgType , imgDim, imgSize],
    "foo":"bar"
}
console.log(JSON.stringify(d));

Output:

{"fizz":"buzz","imgDesc":["PNG","350x150","127 KB"],"foo":"bar"}

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