Chapter 24. JSON
Meanwhile, the JSON is a subset of the literal notation object of JS. Because JSON is a subset of JS, this could be used in the language easily.
In the example above, the object is constructed that contains a one member bindings. This also contains array confining three objects such as regex, method, and ircEvent members.
The members could also be restored using the subscript or dot operators.
The function eval is fast to use. But this could compile and run any JS program, so there could be security concerns. Using eval is signified if the source is competent and trusted. It is a lot more secure to use a JSON parser. In online applications over XMLHttpRequest, communication is allowed only to the same origin, which provides that page, so this will be trusted. But this might not be efficient. When the server is not thorough in encoding JSON, or if this doesn’t validate all the inputs, then it may yield invalid JSON text that can also carry harmful script. The function eval will also run the script, which will unleash the bad script.
To improve your defense, you can use a parser, which will interpret not only JSON text, but will also reject other scripts. In web browsers that offer support, parsers are a lot faster compared to eval. Of course, JSON is also included in the ECMAS standard.
The alternative parameter reviver is a function, which you can call for each key and value at each level of the final outcome. The result of the function reviver will replace every value. You can use this to change generic objects into occurrences of pseudo-classes or to change the date strings into objects Date.
The JSON stringifier will go in the opposing direction, changing the JS data structures into text. JSON will not provide support for cyclic data structures. Hence, be sure that you are careful in not providing cyclical structures to the stringifier.
If the method stringify sees an object, which contains the method toJSON, it will call that method, and will stringify the returned value. This will allow the object to identify its own JSON representation.
The method stringifier may take another string array, which are used to choose the properties that will be added in the JSON text.
The method stringifier could take an optional function replacer. This will be called after toJSON method (if there’s one) on every of the values in the structure. This could be passed every key and value as parameters, and this could be confined to object that holds the key.
The values that are not represented in JSON such as undefined and functions are not incuded.
Numbers that are non-finite are replaced using null. In order to substitute other values, you can use a function replacer such as this code: