Rendering JSON string directly as Javascript object, vs. rendering string for JSON.parse

旧街凉风 提交于 2020-01-03 03:06:07

问题


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

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