Reputation: 26878
Consider the file below being used as input for the accompanying JavaScript used in node.js. The script will fail with "Unexpected token h"
because hello
is not in quotes. Is there a way to parse this file anyway without having to fix the string first?
data.json
{
"foo": "bar",
hello: "world",
"jane": "fonda",
jimmy: "buffet"
}
index.js
/*jslint node:true*/
"use strict";
var fs = require("fs");
fs.readFile("./data.json", "utf8", function (err, data) {
var jsonData = JSON.parse(data);
console.log(jsonData);
});
Upvotes: 2
Views: 267
Reputation: 26878
Wingblade's answer covers how to do this using eval
, which won't run under strict mode
. One alternative is to create a Function
object with the poorly formatted data as the function body:
var f = new Function("return " + data);
var ff = f();
console.log(ff);
This runs under strict mode
, but I'm not sure how far away it is from eval
.
Upvotes: 0
Reputation: 10093
As Vinin Paliath already said, this isn't possible. If incorrect syntax would parse, then it wouldn't be incorrect syntax, would it?
At best, you can try to write a custom function that cleans up common JSON markup mistakes. E.g. that checks for missing quotes like in your examples.
If your JSON is incorrect JSON but would be correct as a javascript object literal, you could use eval. eval('var jsonData = ' + data);
I'd highly advise against this with user-entered data because security concerns, though. e.g. someone putting {};alert("intrusive message");
in data
.
Upvotes: 1