Reputation: 3701
I'm working with the Readline module in NodeJS and would like to parse the content of what the user wrote as code. Meaning if someone writes:
{
name: "David",
age: 34
}
I should be able to JSON.stringify(content)
and get:
{
"name": "David",
"age": "34"
}
How can I convert a string in to actual code, so it can be interpreted as a JavaScript object, thus be converted in to JSON using JSON.stringify()
?
Upvotes: 0
Views: 2431
Reputation: 3701
The trick to make this work is to use the VM module in a undocumented way as seen below.
let vm = require('vm');
let script = new vm.Script('x = ' + full_content);
let sandbox = script.runInThisContext();
converted = JSON.stringify(sandbox);
Basically you have to create a variable that will hold your string (JavaScript), which will be then converted in to proper JavaScript code thanks to .runInThisContext()
.
In this case the x
variable will "disappear" and you don't have to think about that. But if you were to follow the NodeJS documentation example, and use .runInNewContext()
then the x variable wouldn't go away, a you would have your object (in my case at least) assigned to the x
variable.
Hope this helps :)
Upvotes: 1
Reputation: 8990
It's not entirely clear what you're asking, but, would JSON.parse()
help you here? You'll want to wrap it in a try catch in case the input is not valid JSON.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Upvotes: 1