swagneto
swagneto

Reputation: 28

JSON.parse SyntaxError: Unexpected token { while parsing file with JSON

I'm having problems trying to parse a file that has the following text in it:

{ "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" }

This is a Zmap output and node.js keeps choking on everything after the first line. If you remove the second line from the file, there are no errors and the program runs fine.

I want to be able to read the JSON data in the file and be able to reference each key and value and print them out in console.log.

Here's my current code:

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)

Realistically, I would like to put all this data into a database, but I need to solve the problem of reading the file properly.

Upvotes: 0

Views: 1095

Answers (2)

user4698813
user4698813

Reputation:

Like mentioned, the JSON is invalid. But, instead of turning the JSON in the file into an array of objects, you can also process each line, if each object is on a new line:

However, be aware that, like @jsve pointed out, your file would then remain a JSON impostor.

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

Upvotes: 1

Sumner Evans
Sumner Evans

Reputation: 9157

You can't have multiple JSON objects in a file like that. If you want to store 2 objects in JSON you need to add them to an array:

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

You can access each object with their index:

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)

Upvotes: 1

Related Questions