JSON String inside a JSON

我怕爱的太早我们不能终老 提交于 2019-11-29 18:28:36

问题


I want to create a JSON string inside a JSON request. Here is my code,

Fiddle

JS

var x = {
    a: 1,
    b: 'a sample text',
};

var request = {
    t: JSON.stringify(x),
    c: 2,
    r: 'some text'
};

console.log(request);

Can someone help me how to escape the double quotes?

Console

Object {
  t: "{"a":1,"b":"a sample text"}", //This creates a problem, double quotes inside double quotes.
  c: 2, 
  r: "some text"
}

Thanks in advance.


回答1:


That's just the way the browser console shows you the value of a string, by wrapping in double quotes for the output. This is perfectly normal and nothing is broken.

You can test it by transforming your JSON string back to an object and using a property.

console.log( JSON.parse(request.t).b ); // a sample text



回答2:


There is no problem. It's just your console.log that shows all strings by simply delimiting with ".

As you say this request object is used in a JSON request, where it will be JSON.stringifyed another time, with the valid result

{"t":"{\"a\":1,\"b\":\"a sample text\"}","c":2,"r":"some text"}


来源:https://stackoverflow.com/questions/26238796/json-string-inside-a-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!