【问题标题】:JSON.parse SyntaxError: Unexpected token { while parsing file with JSONJSON.parse SyntaxError: Unexpected token { 使用 JSON 解析文件时
【发布时间】:2015-05-10 10:07:54
【问题描述】:

我在尝试解析包含以下文本的文件时遇到问题:

{ "type": "header", "log_level": 3, "target_port": 80, "source_port_first": 32768, "source_port_last": 61000, "max_targets": -1, "max_runtime": 0, "max_results": 0, "iface": "en0", "rate": 0, "bandwidth": 0, "cooldown_secs": 8, "senders": 7, "use_seed": 0, "seed": 0, "generator": 0, "packet_streams": 1, "probe_module": "tcp_synscan", "output_module": "json", "gw_mac": "00:00:00:00:00:00", "source_ip_first": "127.0.0.1", "source_ip_last": "127.0.0.1", "output_filename": ".\/static\/results\/80.json", "whitelist_filename": ".\/static\/whitelist.conf", "dryrun": 0, "summary": 0, "quiet": 1, "recv_ready": 0 }
{ "type": "result", "saddr": "127.0.0.1" }

这是一个 Zmap 输出,并且 node.js 在第一行之后的所有内容都卡住了。如果从文件中删除第二行,则没有错误,程序运行正常。

我希望能够读取文件中的 JSON 数据,并能够引用每个键和值并在 console.log 中打印出来。

这是我当前的代码:

var fs = require('fs');
var filename = './80.json';
var bufferString;

function ReadFile(callback) {
  fs.readFile(filename, 'utf-8', function(err, data) {
    bufferString = data;
    callback();
  }); 
}

function PrintLine() {
  console.log(JSON.parse(bufferString));
}

ReadFile(PrintLine)

实际上,我想把这些数据都放到一个数据库中,但是我需要解决正确读取文件的问题。

【问题讨论】:

  • 这是80.json 的确切内容吗?因为如果是这样,它不是有效的 JSON,因此会出现错误 jsonlint.com 。您有权访问此文件吗?
  • 这不是有效的 JSON,因为这是一个文件中的 两个 JSON 字符串。如果您先在换行符处拆分,您可能可以一一阅读。
  • 你的意思是文件有多行,每行都有一个对象?定义“扼流圈”。
  • 或者,如果您知道每行总是有一个对象,只需将每一行传递给JSON.parse,而不是while 文件。但我不会把那个文件命名为.json

标签: javascript json node.js


【解决方案1】:

如前所述,JSON 无效。但是,除了将文件中的 JSON 转换为对象数组之外,您还可以处理每一行,如果每个对象都在新行上:

但是,请注意,就像 @jsve 指出的那样,您的文件将仍然是 JSON 冒名顶替者。

function PrintLine() {
    var lines = bufferString.split('\n'),
        tmp = [],
        len = lines.length;
    for(var i = 0; i < len; i++) {
        // Check if the line isn't empty
        if(lines[i]) tmp.push( JSON.parse(lines[i]) );
    }
    lines = tmp;
    console.log(lines[0], lines[1]);
}

ReadFile(PrintLine);

【讨论】:

  • 但从技术上讲,该文件不会是 JSON。
  • 嗯,没错。那么该文件就不值得拥有它的.json 扩展名,但我认为如果文件是自动生成的,那么这样做可能会有所帮助。
  • 在这种情况下可能应该更改自动生成逻辑......但继续在 cmets 中讨论它不会有建设性:)。
【解决方案2】:

您不能在这样的文件中包含多个 JSON 对象。如果要在 JSON 中存储 2 个对象,则需要将它们添加到数组中:

[
    { "type": "header", ..., "recv_ready": 0 },
    { "type": "result", "saddr": "127.0.0.1" }
]

您可以通过索引访问每个对象:

var json = JSON.parse(bufferString);
json[0]; // this is the first object (defined on the first line)
json[1]; // this is the second object (defined on the second line)

【讨论】:

    猜你喜欢
    • 2021-09-30
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2013-12-21
    • 2016-07-25
    • 1970-01-01
    相关资源
    最近更新 更多