在读取日志时,JSON从双引号变为单引号

时间:2014-02-18 11:19:46

标签: json node.js parsing logging streaming

使用apache日志(下面)我可以解析出一个JSON:

[2014.02.14_21.24.22.543] other info I don't care about json: {
  "petstore": "store_number_8",
  "dogs":{
    "terrier":{
      "total":2
    }
  },
  "cat":{
    "siamese":{
      "total":5
    }
  }
}

1)这是有效的JSON吗? 2)为什么双引号会变成单引号?

在我阅读之后,解析出JSON,并显示它我得到以下内容:

{
  'petstore': 'store_number_8',
  'dogs':{
    'terrier':{
      'total':2
    }
  },
  'cat':{
    'siamese':{
      'total':5
    }
  }
} 

顺便说一下,我正在使用Node.js'fs.createStream读取日志,然后简单地执行一个控制台(到目前为止我没有进行任何清理,最终我会将其写入文件)。

fs.creatReadStream(logs).pipe(split()).on(data, function(line){
  if(line.match(/json\:/)){
    shouldThisBeValidJSON = JSON.parse(line.slice(line.indexOf('{'), line.length));
    console.log(shouldThisBeValidJSON);
  }

提前谢谢你。

1 个答案:

答案 0 :(得分:2)

console.log不会返回JSON。它返回此对象的人类可读表示。

所以不,它不是JSON,它更接近JSON5。

如果要显示JSON,则必须将字符串传递给console.log,即console.log(JSON.stringify(shouldThisBeValidJSON))

相关问题