简体   繁体   中英

Is there a native JavaScript way to parse a poorly formatted JSON-like string?

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);
});

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. Eg 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. eg someone putting {};alert("intrusive message"); in data .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM