11

Is there a native JavaScript mode for parsing a malformed JSON format string?

 4 years ago
source link: https://www.codesd.com/item/is-there-a-native-javascript-mode-for-parsing-a-malformed-json-format-string.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Is there a native JavaScript mode for parsing a malformed JSON format string?

advertisements

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. 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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK