Home > Net >  Remove "_version": 19, from a string using regex
Remove "_version": 19, from a string using regex

Time:09-26

I'm not familiar with regex, and it would be great to have some help.

I have a string:

string = '{"shippingStyle": "notProvided", "id": "3b0ec9d4-52ff-4ca7-8e66-bfd67f31662c", "_version": 19, "total": 50857, "shippingPrice": 1114}'

and I would like to remove "_version": 19, in order to have

string = '{"shippingStyle": "notProvided", "id": "3b0ec9d4-52ff-4ca7-8e66-bfd67f31662c", "total": 50857, "shippingPrice": 1114}'

I've tried it with:

string = re.sub(r'"_version\S  ', r'', string)

Any suggestions?

CodePudding user response:

Converting the string into json form and deleting the key seems more convenient and reliable for all possible values of _version to me.

import json
string = '{"shippingStyle": "notProvided", "id": "3b0ec9d4-52ff-4ca7-8e66-bfd67f31662c", "_version": 19, "total": 50857, "shippingPrice": 1114}'
x = json.loads(string)
del x['_version']
print(x)

Output

{'shippingStyle': 'notProvided', 'id': '3b0ec9d4-52ff-4ca7-8e66-bfd67f31662c', 'total': 50857, 'shippingPrice': 1114}

CodePudding user response:

If you're ok with turning the string into a dictionary, you can do it this way:

import json

string = '{"shippingStyle": "notProvided", "id": "3b0ec9d4-52ff-4ca7-8e66-bfd67f31662c", "_version": 19, "total": 50857, "shippingPrice": 1114}'

dictionary = json.loads(string)
new_dictionary = {key: value for key, value in dictionary.items() if key != "_version"}
new_string = json.dumps(new_dictionary)
print(new_string)

which prints

{"shippingStyle": "notProvided", "id": "3b0ec9d4-52ff-4ca7-8e66-bfd67f31662c", "total": 50857, "shippingPrice": 1114}

The way it works is by turning your string into a dictionary with the json package. The dictionary has the _version key removed with a dictionary comprehension. Then the result is dumped back to a string.

CodePudding user response:

For completeness, a regex solution:

re.sub(r'"_version": *[0-9] ,? *', '', string)

However unless you have some deep dark secret reason not to parse JSON the way it was supposed to be parsed, you should use one of the other answers.

  • Related