我必须完成此功能,如何用大写的相应名称替换属性名称。
function stringify(v){
function replacer(k,v){
// to be completed
}
return JSON.stringify(v,replacer)
}
console.log(stringify(JSON.parse(process.argv[2])))
例如,命令:
node json_upper_case.js'[{“ city”:“ Milano”,“ Air Quality”:“ red”,“ Temperature”:10},{“ air quality”:“ yellow”,“ Temperature”:20, “海况”:3,“城市”:“热那亚”}]'
预计将输出以下输出:
[{“城市”:“米兰”,“空气质量”:“红色”,“温度”:10},{“空气质量”:“黄色”,“温度”:20,“海况”: 3,“ CITY”:“ Genova”}]
答案 0 :(得分:0)
简单的Array.prototype.map()
以及一些动态属性名称访问即可完成此工作:
let json = `[{
"city": "Milano",
"Air Quality": "red",
"Temperature": 10
}, {
"air quality": "yellow",
"Temperature": 20,
"Sea conditions": 3,
"City": "Genova"
}]`
function keysToUppercase(j) {
if (typeof j === 'string') { // so it works for javascript arrays as well
try {
j = JSON.parse(j);
} catch (err) {
console.error('Invalid JSON input');
console.error(err);
}
}
j = j.map(x => {
for (let prop in x) {
x[prop.toUpperCase()] = x[prop];
delete x[prop];
}
return x;
})
return j;
}
console.log(keysToUppercase(json));
答案 1 :(得分:-1)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter显示了几乎正确的答案,请尝试修改给定的功能以满足您的需求:
function replacer(key, value) {
// Filtering out properties
if (typeof value === 'string') {
return undefined;
}
return value;
}