0

I'm supposed to set up JSON formatted data parsing in a project for IE (exclusively) and I know about this library but the data transfer will be significant issue and I'd like to minimize the amount of bytes moved.

The JSON object I'll be consuming is very small and quite flat, in human terms maybe 30 lines in at most 3 levels of depth.

Is there a better way to approach this? RegEx tends to create more problems than it solves. Any other ideas on how to pick out a value (or a set of values) connected to a node called e.g. shabong?

I'm used to the XDocument class in C# where one only needs to specify the name of a descendant to get a bunch of information contained in a tag. A similar solutions would be preferable. (Old dog, new tricks, hehe.)

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

1 Answers1

1

If you can be guaranteed that the data is secure, then you can use eval or the Function constructor to parse the data.

This is because the JSON data structures and values very closely resemble those found in JavaScript's literal notations, so you can usually resort to evaluating the data as actual JavaScript expressions.


Using eval:

var parsed = eval("(" + myjsondata + ")");

Using Function:

var parsed = (new Function("return " + myjsondata))();

Again, this is only if you're absolutely certain of the integrity of the data being passed. Because you're treating it like part of the program, any malicious code that was substituted for valid data will be executed.

The Function version offers a tiny bit of security in that it's invoked in the global scope, so any malicious code won't have access to local variables. This should offer little comfort overall.


Aside from the above solution, you could always create your own serialization that is specific to the needs of your data. If the data is simple enough, it could offer you the ability to write a very short and fast parser for your custom serialization.

I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • I've tried to follow the example of @Sujay at [this discussion](http://stackoverflow.com/questions/5093582/json-is-undefined-error-in-ie-only) but I can't seem to make it work (and his usage of cryptic variable names make my hair go bye, bye, haha). As for the data source - **yes** I'm 100% sure it's reliable. If it's not - hello law suit against them **big time**. :) – Konrad Viltersten Nov 27 '12 at 15:10
  • @KonradViltersten: You'll need to ask Sujay about that, but if the data is guaranteed to be safe, then I'd just use one of the above. – I Hate Lazy Nov 27 '12 at 15:13
  • Yupp. It worked like a charm. I need to show something working by Friday so I'll go with that. A more elaborate parser, I can develop later, if needed. Thanks! – Konrad Viltersten Nov 27 '12 at 15:50