Ackount 6shots
Ackount 6shots

Reputation: 37

How to append key an item to .json file in Python?

How to append key an item to .json file in Python? (It is not necessary to have format {"Time": "Short"}) I have .json:

{
  "random": [
    {
      "Volume": "Any",
      "Light": "Bright"
    }
  ]
}

I need to add one string "Time": "Short" to get:

  "random": [
    {
      "Volume": "Any",
      "Light": "Bright",
      "Time": "Short"
    }
  ]
}

What i did:

    data = json.load(json_file)
    data["req"].append({"Time": "Short"})
    json.dump(data, json_file, indent=3)

And .json looks like:

{
  "random": [
    {
      "Volume": "Any",
      "Light": "Bright"
    }
  ]
}
  "random": [
    {
      "Volume": "Any",
      "Light": "Bright",
      "Time": "Short"
    }
  ]
}

Upvotes: 0

Views: 50

Answers (1)

Johnny John Boy
Johnny John Boy

Reputation: 3202

I think you may have copied and pasted then tweaked the key but this is essentially what you need:

import json

dict_one = {
  "random": [
    {
      "Volume": "Any",
      "Light": "Bright"
    }
  ]
}

dict_one['random'][0].update(Time="Short")
print(json.dumps(dict_one))
# {"random": [{"Volume": "Any", "Light": "Bright", "Time": "Short"}]}

Your dictionary key "random" is a list of dictionaries, in your example only one. So using dict_one['random'][0].update(Time="Short") we are updating the dictionary key 'random' and [0] relates to the first item in the list.

If you need to update more items in the list then you'd have something like:

import json

dict_one = {
  "random": [
    {
      "Volume": "Any",
      "Light": "Bright"
    },
    {
      "Volume": "Any",
      "Light": "Bright"
    }
  ]
}

for item in dict_one['random']:
    item.update(Time="Short")

print(json.dumps(dict_one))
# {"random": [{"Volume": "Any", "Light": "Bright", "Time": "Short"}, {"Volume": "Any", "Light": "Bright", "Time": "Short"}]}

Upvotes: 1

Related Questions