我有一个带有大量以下值的JSON文件:
"values": [
"Foo": 1,
"Bar": 2,
"Baz": 3,
...
],
如何有效地将其转换为:
"values": [
{
"name": "Foo",
"value": 1
},
{
"name": "Bar",
"value": 2
},
{
"name": "Baz",
"value": 3
},
...
],
任何帮助将不胜感激!
答案 0 :(得分:1)
好的,所以您的输入有两个问题。首先是给定的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(/[\r\n]/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个空格,以保持可读性。
答案 1 :(得分:0)
使用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]]
})
}
答案 2 :(得分:0)
如果您打算使用接收到的数据,即使用connection.query(your_custom_sql_query, (err, rows, fields)
从数据库中获取数据(例如MSSql,MySql ...)
有关更多信息:
Node.js MySQL Select From Table
我建议您使用:
const myJson = JSON.stringify(rows[0]);