如何编写脚本来编辑JSON文件? [英] how to write a script to edit a JSON file?

查看:273
本文介绍了如何编写脚本来编辑JSON文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个名为 people.json 的文件。其内容为:

For example I have a file called people.json. Its content is:

[
  {"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"
}
]

如何编写脚本以向每个人添加 pic 键并添加person.name .lowercase +。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?

在流程结束时,将编辑people.json并将其保存到硬件而不是内存中。

At the end of the process, the people.json will be edited and saved into the hardware and not memory.

非常感谢。

推荐答案

这是一个完整的程序,用JavaScript(使用node.js),做你想做的事: / p>

Here's a complete program, in JavaScript (using node.js), doing what you want :

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));

作为奖励(包括其他语言的其他回答者),这里有一个固定的输入JSON:

And as a bonus (including for other answerers with other languages), here's a fixed input JSON :

[
    {"name":"Paul","age":29},
    {"name":"Kathy","age":101},
    {"name":"Paula","age":12},
    {"name":"Bruce","age":56}
]

这篇关于如何编写脚本来编辑JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆