【问题标题】:Rename variables at different levels of nested JSON dataset重命名嵌套 JSON 数据集不同级别的变量
【发布时间】:2016-01-17 19:18:28
【问题描述】:

我希望根据嵌套 JSON 数据集中的级别,用不同的名称重命名变量。

一个示例 JSON 文件如下:

[
  {
    key: "John Doe School",
    values: [
      {
        key: "Mr. Brown",
        values: [
          {
            key: "Joe",
            TestScore: 95
          },
          {
            key: "Sarah",
            TestScore: 99
          }
        ]
      }
    ]
  }
]

在这个例子中,我想将一级“key”改为“School”,二级“key”改为“Teacher”,第三级“key”改为“Student”。

更改后的 JSON 数据集如下所示:

[
  {
    School: "John Doe School",
    values: [
      {
        Teacher: "Mr. Brown",
        values: [
          {
            Student: "Joe",
            TestScore: 95
          },
          {
            Student: "Sarah",
            TestScore: 99
          }
        ]
      }
    ]
  }
]

【问题讨论】:

  • 你试过什么?
  • 我尝试从以下两个帖子中实施解决方案:1.) stackoverflow.com/questions/21148419/…, 2.) stackoverflow.com/questions/4647817/…。但是,它们似乎并没有解决嵌套问题,因为“key”在每个级别都会以相同的方式重命名。
  • 所以?你有什么问题?
  • 以上链接没有解决嵌套问题,因为“key”在每个级别都会以相同的方式重命名。

标签: javascript json d3.js


【解决方案1】:

好吧,鉴于你的例子,你可以这样做......

var json = [
  {
    key: "John Doe School",
    values: [
      {
        key: "Mr. Brown",
        values: [
          {
            key: "Joe",
            TestScore: 95
          },
          {
            key: "Sarah",
            TestScore: 99
          }
        ]
      }
    ]
  }
];

json[0].key = "School";
json[0].values[0].key = "Teacher";
json[0].values[0].values[0].key = "Student";
json[0].values[0].values[1].key = "Student";

更新以下评论

json[0]['School'] = json[0].key; // Add new key:value
delete json[0].key; // Delete previous one

json[0].values[0]['Teacher'] = json[0].values[0].key; // Add new key:value
delete json[0].values[0].key; // Delete previous one

json[0].values[0].values[0]['Student'] = json[0].values[0].values[0].key; // Add new key:value
delete json[0].values[0].values[0].key; // Delete previous one

json[0].values[0].values[1]['Student'] = json[0].values[0].values[1].key; // Add new key:value
delete json[0].values[0].values[1].key; // Delete previous one

我假设您将循环遍历许多不同的 JSON 对象,因此您当然也需要实现它,但上述结构应该为您指明正确的方向;)

【讨论】:

  • 非常感谢您的建议。问题是这个解决方案覆盖了与“key”相关的值,而不是“key”的变量名。见这里:jsfiddle.net/nyan22/u0qnj7vb/6。我重新发布了这个问题,以使其所需的输出更加清晰。
  • 非常感谢。这个解决方案帮了大忙!
  • :) 很高兴它有帮助...快乐编码!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 2017-05-03
  • 2016-12-29
  • 1970-01-01
相关资源
最近更新 更多