-1

I need to replace an integer in a json body:

file1.json
{
    "id": 0,
    "col_1": "some value",
    "col_2": "another value"
}

I know to replace a string, I would use:

import json

with open('file1.json') as f:
    data = json.load(f)

data["col_1"] = data["col_1"].replace("some value", "new value")

But how would I replace the id, to the number 5 for example?

JD2775
  • 3,658
  • 7
  • 30
  • 52

1 Answers1

1

You've got the right idea! Loading in the json as a string with json.load(path) and then manipulating the data in the instance is certainly the easiest way to do it. As the comments said, you can set that value with data["Column name"] = new value since once the data is read into python it's held as a dictionary.

What you need to do then is save the manipulated data item to .json, IIRC the function you're looking for is json.dump

I found a related post here: How do I write JSON data to a file?

Sand
  • 198
  • 11