1

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?

Brian Rak
  • 4,912
  • 6
  • 34
  • 44
  • I've done this sort of thing before, you should be fine. – Brian Glaz Aug 12 '15 at 20:06
  • 1
    Haha, for a split second, I thought the comment above me was from OP. Yes, you should be fine. I've also had the case with very large Objects, and never had a problem. If the Object is big, you might as well not have to parse it again client-side. JSON is meant to travel alone. To transmit data by itself in a unified format. If you send it along with JS code that will handle it, there is no reason not to use an Object literal. A very good example of it is [JSONP](http://stackoverflow.com/questions/2067472/what-is-jsonp-all-about). – blex Aug 12 '15 at 20:11
  • Maybe you could send it as a separate JSON file. – David Knipe Aug 12 '15 at 22:12
  • Thanks for the replies, everyone. @blex When you say "very large Objects," how big do you mean? Some of my literals are 300K or more. (I don't know why that feels particularly big to me but it does.) – Brian Rak Aug 12 '15 at 22:50
  • 1
    The biggest I can recall was about 250-280KB, but 300KB or more should not be a problem ([This thread](http://stackoverflow.com/questions/4833480/have-i-reached-the-limits-of-the-size-of-objects-javascript-in-my-browser-can-ha) talks about several MB, the guy has a 44MB array and is running out of parsing memory, the answer suggests to split it into 20MB parts). – blex Aug 13 '15 at 07:37
  • Is there a function or an easy way to write an object literal like that (as opposed to JSON.stringify), or do I need to write a recursive function to print out the object literal? – Tim McMackin Jul 02 '19 at 17:18

0 Answers0