【问题标题】:when reading logs, JSON changes from double quotes to single quotes读取日志时,JSON由双引号变为单引号
【发布时间】:2014-03-18 02:39:33
【问题描述】:

通过 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);
  }

提前谢谢你。

【问题讨论】:

    标签: json node.js parsing logging streaming


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2015-12-18
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      • 2018-01-07
      • 2015-10-29
      相关资源
      最近更新 更多