简体   繁体   English

是否有原生 JavaScript 方法来解析格式不佳的类似 JSON 的字符串?

[英]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.考虑以下文件用作 node.js 中使用的随附 JavaScript 的输入。 The script will fail with "Unexpected token h" because hello is not in quotes.该脚本将失败并显示"Unexpected token h"因为hello不在引号中。 Is there a way to parse this file anyway without having to fix the string first?有没有办法解析这个文件而不必先修复字符串?

data.json数据.json

{
    "foo": "bar",
    hello: "world",
    "jane": "fonda",
    jimmy: "buffet"
}

index.js索引.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.正如 Vinin Paliath 已经说过的,这是不可能的。 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.充其量,您可以尝试编写一个自定义函数来清除常见的 JSON 标记错误。 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.如果您的 JSON 是不正确的 JSON,但作为 javascript 对象文字是正确的,您可以使用 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");例如有人把{};alert("intrusive message"); in data .data

Wingblade's answer covers how to do this using eval , which won't run under strict mode . Wingblade 的回答涵盖了如何使用eval来做到这一点,它不会在strict modestrict mode One alternative is to create a Function object with the poorly formatted data as the function body:一种替代方法是创建一个以格式错误的数据作为函数体的Function对象:

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 .这在strict modestrict mode ,但我不确定它离eval多远。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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