5
votes

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

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?

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

Thank you very much.

1
In any of those language, this is a few lines of code. Choose the one you prefer. - Denys Séguret
For a correct JSON, you're missing some commas. - Denys Séguret
I'm very new to this. May you please give me some hints? - dazer
@dystroy, they're not missing, just in the wrong place :) - John La Rooy
@user2724559, If you had given correct JSON in the original question, you would have answers already - John La Rooy

1 Answers

9
votes

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

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}
]