0

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

1 Answer 1

1

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"}]}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.