use javascript eval() function to convert json text string into an object

To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parenthesis to avoid tripping on an ambiguity in JavaScript's syntax.

for example,



var json_text = "{type:'select',rate:'10',free:'0',oprtation:'+',value:'1'}";
var json_object = eval('(' + json_text + ')');

Here is the formal definition of eval function :


The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not trustfully accurate in its JSON encoding, or if it does not seriously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

eval()  Definition and Usage

The eval() function evaluates and/or executes a string of JavaScript code.
First, eval() determines if the argument is a valid string, then eval() parses the string looking for JavaScript code. If it finds any JavaScript code, it will be executed.

Syntax

eval(string)

Parameter Description
string Optional. The string to be evaluated/executed

0 comments :: use javascript eval() function to convert json text string into an object

Post a Comment