0

I have an invalid json string that contains variables in a specific format.

A variable start with 'VV' then key (only alphanumeric, * and _ characters) then ends with 'VV'.

There are some places where these variables are defined in invalid json string, that can in inside value of any property or inside array.

I have to bring all variables inside the double quotes, if they are not already. So that the json string becomes a valid one.

One can assume that if all such variable is resolved, the json becomes a valid one.

My sandbox is https://regex101.com/r/uE9vB2/6

I have spent so much time but i could not found a way to get this issue resolved.

PS : I am not able to resolve the array entities. Edit : Grouping is not required, as i am using separate grouping structure. I just want to replace those variable with "was-a-var" for both in objects and array.

for input :

{
  "arr1": [
    "key9",
    VVvariable1VV,
    "VVvariable2VV"
    "key6",
    "key7"
  ],
  "obj1": {
    "key1": "VVvaria*ble3VV",
    "key3": VVvariable4VV,
    "key7": "value7"
  },
  "obj2": {
    "key1": {
      "key1": "value-changed",
      "key5": "VVvari_able5VV",
      "key6": "value6",
      "key7": VV*VV
    },
    "key2": [
      "VVvariableVV",
      VV*VV
    ]
  },
  "key8" : "value",
  "key3": VVvariableVV,
  "key5": "VVvariableVV"
}

Expected string :

{
  "arr1": [
    "key9",
    "was-a-var",
    "VVvariable2VV"
    "key6",
    "key7"
  ],
  "obj1": {
    "key1": "VVvaria*ble3VV",
    "key3": "was-a-var",
    "key7": "value7"
  },
  "obj2": {
    "key1": {
      "key1": "value-changed",
      "key5": "VVvari_able5VV",
      "key6": "value6",
      "key7": "was-a-var"
    },
    "key2": [
      "VVvariableVV",
      "was-a-var"
    ]
  },
  "key8" : "value",
  "key3": "was-a-var",
  "key5": "VVvariableVV"
}

Edit : javascript regex only.

1 Answer 1

2

You can use the following to match:

(?<!")VV[\w*]*?VV(?!")

And replace with the following:

"was-a-var"               

See RegEx DEMO

Edit: For javascript:

([^"])VV[\w*]*?VV(?!")

and replace with:

$1"was-a-var"

See DEMO

Sign up to request clarification or add additional context in comments.

6 Comments

@codeofnode updated the answer too check the demo :)
nice answer.. but just one more request. I don't want any grouping, removing () give error
you can remove grouping if you dont want to use it in the replacement
i am happy with was-a-var.. but no grouping
yes.. but you might have to use grouping.. is that ok?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.