【问题标题】:Getting json fields from json file从 json 文件中获取 json 字段
【发布时间】:2022-10-17 23:29:52
【问题描述】:

我面临一个问题。我有这个 json 日志

{
  "log": "Log Info     : { \"datetime\" : \"datetime\", \"field1\" : \"value1\", \"field2\" : \"value2\", \"field3\" : \"value3\", \"field4\" : \"value4\", \"field5\" : \"value5\", \"field6\" : \"value6\", \"field7\" : \"value7\", \"field8\" : \"value8\", \"field9\" : \"value9\", \"field10\" : \"value10\", \"field11\" : \"value11\"}\n",
  "stream": "stdout",
  "kubernetes": {
    "pod_name": "pod_name",
    "namespace_name": "namespace_name",
    "pod_id": "pod_id",
    "host": "host",
    "container_name": "container_name",
    "docker_id": "docker_id",
    "container_hash": "container_hash",
    "container_image": "container_image"
  }
}

我需要获取“log”键中的所有字段。这些字段会增加,所以我需要动态获取日志中的所有字段。我正在使用此代码来解析 json,但输出是这样的。也许有人可以帮助我?谢谢。

const readFile = require("fs").readFile;

readFile("log.json", (err, data) => {
  if (err) throw err;
  const log = JSON.parse(data);
  console.log(log);
});

输出:

{
  log: 'Log Info     : { "datetime" : "datetime", "field1" : "value1", "
field2" : "value2", "field3" : "value3", "field4" : "value4", "field5" :
 "value5", "field6" : "value6", "field7" : "value7", "field8" : "value8"
, "field9" : "value9", "field10" : "value10", "field11" : "value11"}\n',
  stream: 'stdout',
  kubernetes: {
    pod_name: 'pod_name',
    namespace_name: 'namespace_name',
    pod_id: 'pod_id',
    host: 'host',
    container_name: 'container_name',
    docker_id: 'docker_id',
    container_hash: 'container_hash',
    container_image: 'container_image'
  }
}

【问题讨论】:

  • 为什么log这个奇怪的“东西”的值应该只是另一个对象,而不是带有一些前缀的JSON,这使得它无效?
  • 这是一种不幸的格式,因为log 的值不是有效的JSON,给定'Log Info : 文本。您必须使用子字符串操作来提取 {} 之间的字符串并将其解析为 JSON。
  • 到目前为止,您尝试过什么来自己解决这个问题? -> How much research effort is expected of Stack Overflow users?
  • 我也尝试过使用正则表达式。

标签: javascript node.js json


【解决方案1】:

您还需要JSON.parse 还需要“内部”json(从前缀中清除它之后)

var obj = {
  "log": "Log Info     : { "datetime" : "datetime", "field1" : "value1", "field2" : "value2", "field3" : "value3", "field4" : "value4", "field5" : "value5", "field6" : "value6", "field7" : "value7", "field8" : "value8", "field9" : "value9", "field10" : "value10", "field11" : "value11"}
",
  "stream": "stdout",
  "kubernetes": {
    "pod_name": "pod_name",
    "namespace_name": "namespace_name",
    "pod_id": "pod_id",
    "host": "host",
    "container_name": "container_name",
    "docker_id": "docker_id",
    "container_hash": "container_hash",
    "container_image": "container_image"
  }
}

var str = (obj.log).substring(obj.log.indexOf(':') + 1);
//console.log(str)
var result = JSON.parse(str);
console.log(result)

【讨论】:

  • 切片有点聪明,尽管这样的解决方案可能会随着时间的推移而中断。
  • 那就不聪明了。我将更改为 substrsubstring,这是不被弃用的。
猜你喜欢
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多