Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute a javascript code inside a json object?

is there away?

so something like:

{ key1 : "val1", key2: "val2", some_code: "document.getElementById("someid").innerHTML='test';" }

So some_code would be executed without any user intervention?

like image 724
David Ang Avatar asked Jan 31 '11 10:01

David Ang


People also ask

Can JSON execute JavaScript?

It is worth keeping in mind that JSON was developed to be used by any programming language, while JavaScript objects can only be worked with directly through the JavaScript programming language. In terms of syntax, JavaScript objects are similar to JSON, but the keys in JavaScript objects are not strings in quotes.

Can you run code in JSON?

As below, yes you could.

Can you write to a JSON file in JavaScript?

JavaScript provides a built-in JSON object for parsing and serializing JSON data. You can use the JSON. stringify() method to convert your JSON object into its string representation, and then use the file system fs module to write it to a file.

Can JSON have functions?

In addition, JSON can not contain functions. Any JSON text must contain valid JavaScript expressions. In some browser engines, the U+2028 line separator and U+2029 paragraph separator are allowed in string literals and property keys in JSON, but when using them in JavaScript code will result in SyntaxError.


1 Answers

No.

First of all, your example isn't valid JSON. Try it out at JSON validator.

Second of all, JSON is a data exchange standard and when properly parsed, any text that inside of it that is some code will not be executed.

Read on JSON security issues.

Rule of thumb: don't use JavaScript eval function, rather use a ready made parser such as Douglas Crockford's JSON evaluator.

like image 90
darioo Avatar answered Sep 29 '22 01:09

darioo