Home > Enterprise >  changing a string in json with python
changing a string in json with python

Time:05-21

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

CodePudding user response:

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

CodePudding user response:

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"

CodePudding user response:

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

  • Related