Ruby Regex to find and replace key field where value field is missing in KV pair


(Tufail Ahmad) #1

I have a JSON to start with where there are key fields that may or may not have value field; I have to remove those keys. Example JSON:
str= '{"key1": "val1_start_:,?val1end", "key2": "key3": "val3_start:,?val3end", "key4": "value4", "key5": "value5", "key6" : "key7": "value7"}'
Here I have to remove key2 and key6 to make it a valid json.
The expected output would be something like this
{"key1": "val1_start
:,?val1end", "key3": "val3_start:,?_val3end", "key4": "value4", "key5": "value5", "key7": "value7"}

How to do this in Ruby/regex?
I thought of splitting based on : or , but colons and commas can be part of my value field.
Any ruby regex would be preferred, Please help !


(Guy Boertje) #2

Perhaps...

("\S+"\s?:\s?)(?:"\S+"\s?[^,])

See http://rubular.com/r/QviWx9SO9B


(system) #3

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.