重新构造JSON文件中的大量值



我有一个JSON文件,其中包含大量以下值:

"values": [
"Foo": 1,
"Bar": 2,
"Baz": 3,
...
],

如何有效地将其转换为:

"values": [
{
"name": "Foo",
"value": 1
},
{
"name": "Bar",
"value": 2
},
{
"name": "Baz",
"value": 3
},
...
],

任何帮助都将不胜感激!

好的,您的输入有两个问题。第一个是给定的JSON无效,因此无法直接解析。"values"后面的方括号应该是花括号,以允许使用哈希而不是数组:

let raw_old_data =
// Read the old file
fs.readFileSync('./input_data.json').toString()
// Remove all newlines which could interfere with the regex
.replace(/[rn]/g, '')
// Replace the square brackets after `"values"` with curly braces
.replace(/"values": [(.+?)]/g, '"values": { $1 }');

要将这个(现在有效的(字符串转换为JSON对象,可以使用JSON.parse:

let old_data = JSON.parse(raw_old_data);

第二个问题是存储值的格式与您的需要不匹配。您希望从{ key: "value" }转换为[ name: "key", value: "value" ]。以下函数可以做到这一点,假设您的Node版本支持ES6(如果不支持,请查看Murillo的答案(:

function fix_format(obj) {
// This is where we keep the new items in the correct format
let res = [];
// Loop over all values
Object.keys(obj.values).forEach(name => {
let value = obj.values[name];
// Change the format and add to resulting array
res.push({
// If the variable is the same as the key of the hash, it doesn't have to be specified
name,
value,
});
});

return res;
}

然后剩下要做的就是通过Array.map函数循环旧对象中的所有数据:

let new_data = old_data.map(fix_format);

并有选择地将其写回一个文件,用于不同的程序:

fs.writeFileSync('./formatted_data.json', JSON.stringify(data, null, 2));

注意JSON.stringify函数中的2表示生成的JSON应填充2个空格,以保持可读性。

使用ES6:

Object.keys(values).map(name => ({
name,
value: values[name]
}))

无ES6:

var keys = Object.keys(values);
var newValues = [];
for(var i = 0; i < keys.length; i++){
newValues.push({
name: keys[i],
value: values[keys[i]]
})
}

如果您打算使用接收到的数据,即使用connection.query(your_custom_sql_query, (err, rows, fields)从数据库(例如MSSql、MySql…(获取数据

了解更多信息:
Node.js MySQL从表中选择

我建议您使用:
const myJson = JSON.stringify(rows[0]);

最新更新