javascript 如何编写脚本来编辑 JSON 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18508834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to write a script to edit a JSON file?
提问by dazer
For example I have a file called people.json
. Its content is:
例如,我有一个名为people.json
. 其内容是:
[
{"name": "Paul",
"age": 29,
},
{"name": "Kathy",
"age": 101,
},
{"name": "Paula",
"age": 12,
},
{"name": "Bruce",
"age": 56,
}
]
so here I wanted to add a picture link for each person for example
所以在这里我想为每个人添加一个图片链接,例如
[{"name":"Paul",
"age" : 29,
"pic" : "paul.png"
},
{"name": "Kathy",
"age": 101,
"pic" : "kathy.png"
},
{"name": "Paula",
"age": 12,
"pic" : "paula.png"
},
{"name": "Bruce",
"age": 56,
"pic" : "bruce.png"
}
]
How do I go about writing a script to add a pic
key into each person and add in a person.name.lowercase + ".png" as a value?
我如何编写脚本来pic
为每个人添加一个键并添加一个 person.name.lowercase + ".png" 作为值?
At the end of the process, the people.json will be edited and saved into the hardware and not memory.
在该过程结束时,people.json 将被编辑并保存到硬件而不是内存中。
Thank you very much.
非常感谢你。
回答by Denys Séguret
Here's a complete program, in JavaScript (using node.js), doing what you want :
这是一个完整的 JavaScript 程序(使用 node.js),可以执行您想要的操作:
fs = require('fs');
var m = JSON.parse(fs.readFileSync('people.json').toString());
m.forEach(function(p){
p.pic = p.name.toLowerCase()+".png";
});
fs.writeFile('people.json', JSON.stringify(m));
And as a bonus (including for other answerers with other languages), here's a fixed input JSON :
作为奖励(包括使用其他语言的其他回答者),这是一个固定的输入 JSON :
[
{"name":"Paul","age":29},
{"name":"Kathy","age":101},
{"name":"Paula","age":12},
{"name":"Bruce","age":56}
]