views:

205

answers:

5

So, I have a json file and I want to get the names of all the fields in the file using javascript. Is there a better way other than using eval and then using reflection on the resulting object? Or does that make no sense? Thanks.

+2  A: 

Unless you want to parse the text somehow I would suggest the easiest way being to eval it and the loop though it to get all the field names.

Adam Peck
+1  A: 

Well, it would get tricky, because of nesting and such. It depends on your structure. And javascript's "reflection" doesn't have any performance hit, so feel free to walk through the object's members. Or you could roll your own parser based on the JSON specs.

Mufasa
+3  A: 

You should do what some frameworks use, like:

http://www.prototypejs.org/api/string/evalJSON

It checks if the JSON is sanitized. But other than that its just using old plain eval() at the end.

Luca Matteis
+1  A: 

Note, there is a proposal for a JSON Schema, defined in JSON. They even have a validator up on Google code, so you might find use of this even now.

Zach
A: 

A JSON file doesn't really need to comply with a consistent schema. There can be ragged rows; elements can vary in sequence across rows; any row can have any elements (or none). All in hierarchical-node fashion. So coming up with what you want by ad hoc inspection (reflection) could be pretty dicey.

Not to say that any parties involved in using a JSON format couldn't put more structural requrements in place, but then you'd have the schema to start with.

le dorfier