-3

how do i replace number inside "id": "1", and increment the number by +1 also remove the quotes around the number "id": 1 should look like this.

Here is an example of the json file, but it's huge. So doing this automatic by python would save alot of time

[
    {
      "id": "1",
      "text": "How old can a sea turtle get?",
    },
    {
      "id": "2",
      "text": "How many fishes are in the lake?",
    }
]

This is how far i got:

import re

with open("new 2.txt") as file:
    for line in file.readlines():
        x = re.findall('"id": "[a-zA-z]{0,1}[0-9]*"', line)
Printer
  • 457
  • 3
  • 11
  • You don't use regex. You use the `json` module to read the json file into a python object, find all dictionaries that have the `id` key, and increment their values. Then you dump that object back to the json file – Pranav Hosangadi Oct 26 '21 at 18:32
  • Start by reading [How to parse data in JSON format?](https://stackoverflow.com/q/7771011/4046632) – buran Oct 26 '21 at 18:32
  • Also note that the excerpt of the json file you have shown is not valid json. People will be able to write better answers if you share an excerpt that is valid and representative of your actual file. – Pranav Hosangadi Oct 26 '21 at 18:34

1 Answers1

3

Use the json module, not regex.

import json

with open('new.txt') as f:
    records = json.load(f)
for item in records:
    item['id'] = int(item['id']) + 1
with open('updated.txt') as f:
    json.dump(records, f, indent=4)

Et voila:

[
    {
        "id": 2,
        "text": "How old can a sea turtle get?"
    },
    {
        "id": 3,
        "text": "How many fishes are in the lake?"
    }
]
tzaman
  • 46,925
  • 11
  • 90
  • 115