python how do I add string to json array

Viewed 34

So I have this data.json file

{
  "names": [
    {
      "firstnames": ["Jim", "Joe", "Emma"]
    }
  ]
}

I want to add more names in "firstnames". Like if I want to add Gary the array would look like this: ["Jim", "Joe", "Emma", "Gary"]. I tried with the json module but it only rewrote it or added a new key

1 Answers

You can use append:

d= {
"names": [
    {
      "firstnames": ["Jim", "Joe", "Emma"]
    }
  ]
}
d["names"][0]["firstnames"].append("Gary")
print(d)
# {'names': [{'firstnames': ['Jim', 'Joe', 'Emma', 'Gary']}]}
Related