'changing a string in json with python
so I am trying to change every "cat" word with "dog" but when I try to execute my code it just doesn't change anything
here is my code catisnotpillar.py
import json
import re
with open("catisnotpillar.json", "r+") as f:
cattext = f.read()
f.seek(0)
cattext.replace("cat\b", "dog")
f.write(cattext)
print(cattext)
here is the json file catisnotpillar.json
{
"dog": "bob",
"doga": "dog-eater",
"animals": [
"dog",
"dog",
"bat",
"cat",
"caterpillar"
]
}
Solution 1:[1]
Depending on how you'd like to handle "cat", I changed cat\b to "cat" so it only matches strings.
#!/usr/bin/env python
with open("catisnotpillar.json", "r+") as f:
cattext = f.read()
f.seek(0)
cattext = cattext.replace('"cat"', '"dog"')
f.write(cattext)
print(cattext)
Output:
{
"dog": "bob",
"doga": "dog-eater",
"animals": [
"dog",
"dog",
"bat",
"dog",
"caterpillar"
]
}
Solution 2:[2]
with open("catisnotpillar.json", "r+") as f:
cattext = f.read()
f.seek(0)
cattext.replace("\"cat\"", "\"dog\"")
f.write(cattext)
print(cattext)
This
"\"cat\""
matches all the occurrences of
"cat"
Solution 3:[3]
Try this one
import json
count = 0
with open("catisnotpillar.json", "r+") as f:
cattext = json.load(f)
for i in cattext["animals"]:
if i == "cat":
cattext["animals"][count] = "dog"
count += 1
f.seek(0)
json.dump(cattext, f, indent=4)
Output
{
"dog": "bob",
"doga": "dog-eater",
"animals": [
"dog",
"dog",
"bat",
"dog",
"caterpillar"
]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tony N |
| Solution 2 | FLAK-ZOSO |
| Solution 3 | amd |
