本文介绍了重组JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一个json文件,其中存储了以下数据:

Currently I have a json file with multiple data stored as follows:

{"name": ["Adelphi University"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ["Yes: CR"], "mail": ["$40"], "schoolr": ["Yes"]}

该行应该代表一所大学(因此而得名),名称"后的变量(即"supp","online"等)是该学校的属性.我将如何重组该数据,以使名称"变量定义数据,而其他变量作为名称"父级的文件.我的数据应如下所示:

This line is supposed to represent a university (hence the name) and the variables following "name", i.e. "supp", "online" etc., are attributes of that school. How would I restructure this data to have the "name" variable define the data and the other variables be cildren of the "name" parent. My data should look like this:

{
  "schools": {
    "Adelphi University": {
      "supp": "Yes: E, WS",
      "ed": "\u00a0",
      "online": "$40",
      "ea": "12/1",
      "mid": "No",
      "rd": "Rolling",
      "recs": "Yes: CR",
      "mail": "$40",
      "schoolr": "Yes",
    },
    "Dartmouth College": { ... },
    "Harvard University": { ... }
  }
}

我该怎么做?

推荐答案

您可以迭代键并测试name,然后使用名称构建对象并分配一个临时对象.否则,请赋值.

You could iterate the keys and test for name, then build an object with the name and assign a temp object. Otherwise assing the values.

var array = [{ "name": ["Adelphi University"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ["Yes: CR"], "mail": ["$40"], "schoolr": ["Yes"] }, { "name": ["Dartmouth College"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ["Yes: CR"], "mail": ["$40"], "schoolr": ["Yes"] }],
    schools = {},
    result = { schools: schools };

array.forEach(function (a) {
    var temp = {};
    Object.keys(a).forEach(function (k) {
        if (k === 'name') {
            schools[a[k][0]] = temp;
            return;
        }
        temp[k] = a[k][0];
    });
});

console.log(JSON.stringify(result));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于重组JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:59