问题
I have objects that I serialize into JSON strings on the server side for consumption by my JavaScript code. I then deliver these to the client along with the HTML content so that they are immediately available. I had been writing them into the response as strings that I then parse with JSON.parse
, like this:
var json = "{ \"someKey\":\"someValue\" }"; // This string written in by server-side code
var parsed = JSON.parse(json);
Then it occurred to me that this is a waste of time, since I could just directly write the JSON string as a literal JavaScript object, like this:
var someObject = { "someKey" : "someValue" }; // This literal written in by server-side code
This saves the step of escaping the quotes in the string, followed by the step of parsing it back to an object.
I control the JSON rendering on the server side, and I never deliver strings that users have supplied. This seems like a no-brainer. But are there any gotchas to look out for -- any maximum sizes for JavaScript literal objects or anything like that?
来源:https://stackoverflow.com/questions/31974307/rendering-json-string-directly-as-javascript-object-vs-rendering-string-for-js