1

Can I execute script from json file? For example:

helloworld.json
{
"script" : "console.log('helloworld');"
}

I want to run the script in the json file in my html or js file.

OBWang
  • 13
  • 4
  • 2
    You might need to provide more details on your use case and surrounding code. You might also want to check `eval`. – jaibatrik Feb 18 '20 at 06:53
  • 1
    You could try using `eval()`, but this is highly discouraged due to a security risk! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval – Natrium Feb 18 '20 at 06:55
  • you can find solution [here](https://stackoverflow.com/questions/939326/execute-javascript-code-stored-as-a-string) – Tulshi Das Feb 18 '20 at 06:57

2 Answers2

1

Point eval to the string to execute it as code

var json = {"script":"console.log('helloworld');"}
eval(json["script"])

Also see Execute JavaScript code stored as a string

Shaun Webb
  • 426
  • 5
  • 10
  • 2
    Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval! – Natrium Feb 18 '20 at 06:57
  • 1
    Of course! You are just executing code that could have been edited by anyone. A use case may be a single one time test or for experimental reasons. Doesn't mean it should be used in production software. – Shaun Webb Feb 18 '20 at 07:03
1

Yes, you have to:

  1. Load your json file
  2. Execute the script using eval()

Whether that's a good idea or not though depends on your specific use case.

Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
  • Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval! – Natrium Feb 18 '20 at 06:56