-4

I have a string that is not legal to use for json.dump() and I need to edit it. I need to replace the numbers into the string from 0: to "0:" for esxample. Same for 1 and the other numbers that follow.

This string changes from time to time and the numbers can change as well

{"aclList": {0: {"sequence": {1: {"counterData": …etc etc

Must become:

    {"aclList": {"0": {"sequence": {"1": {"counterData": …etc etc

I believe I need to find \d: and replace the match with himself plus the qoutes ""

  • 1
    What have you tried? What didn't work? What did you get? What did you expect? What doesn't work with your code and where is it? – Toto Feb 21 '20 at 15:00

2 Answers2

1

This should solve 99% of your problem:

(?<={)(\d+)(?=:)

https://regex101.com/r/96ReYn/1/ (see https://regex101.com/r/96ReYn/1/codegen?language=python for code)

  • (?<={) - make sure the previous char is a open curly brace
  • (\d+) - grab all digits
  • (?=:) - make sure the next char is a colon

The 1% it will fail against is for data such as "I'm going to mess {3: up your day" so hopefully it doesn't exist in your "JSON".

MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
-1

Yes, you can do it like that:

s = '{"aclList": {0: {"sequence": {1: {"counterData": …etc etc'
for x in re.findall('\d', s):
    s = s.replace(x, f'"{x}"')
alec
  • 5,799
  • 1
  • 7
  • 20