我在尝试解析其中包含以下文本的文件时遇到问题:
$( '#tabs' ).tabs({
disabled: [1, 2, 3, 4, 5],
effect: 'ajax',
autoHeight: true,
autoWidth: true,
contentAnimTime: 600,
contentEasing: 'easeInOutExpo',
tabsAnimTime: 300
});
这是一个Zmap输出,node.js在第一行之后的所有内容上都会阻塞。如果从文件中删除第二行,则没有错误,程序运行正常。
我希望能够读取文件中的JSON数据,并能够引用每个键和值,并在console.log中打印出来。
这是我目前的代码:
{ "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" }
实际上,我想把所有这些数据都放到数据库中,但我需要解决正确读取文件的问题。
答案 0 :(得分:1)
您不能在这样的文件中拥有多个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)
答案 1 :(得分: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);