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

**URL:** <https://discuss.elastic.co/t/ruby-regex-to-find-and-replace-key-field-where-value-field-is-missing-in-kv-pair/113325>\
**Category:** Logstash\
**Created:** [December 27, 2017, 2:43pm UTC](https://discuss.elastic.co/t/ruby-regex-to-find-and-replace-key-field-where-value-field-is-missing-in-kv-pair/113325 "2017-12-27T14:43:27Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![elk\_chaser](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/elk_chaser/32/76982_2.png) [@elk\_chaser](https://discuss.elastic.co/u/elk_chaser)\
**Post date:** [December 27, 2017, 2:43pm UTC](https://discuss.elastic.co/t/ruby-regex-to-find-and-replace-key-field-where-value-field-is-missing-in-kv-pair/113325/1 "2017-12-27T14:43:27Z")

</div>

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 !

---

<div class="post-metadata">

**Author:** ![guyboertje](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/guyboertje/32/31592_2.png) [@guyboertje](https://discuss.elastic.co/u/guyboertje)\
**Post date:** [January 2, 2018, 6:08pm UTC](https://discuss.elastic.co/t/ruby-regex-to-find-and-replace-key-field-where-value-field-is-missing-in-kv-pair/113325/2 "2018-01-02T18:08:55Z")

</div>

Perhaps...

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

```

See [http://rubular.com/r/QviWx9SO9B](http://rubular.com/r/QviWx9SO9B)

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [January 30, 2018, 6:09pm UTC](https://discuss.elastic.co/t/ruby-regex-to-find-and-replace-key-field-where-value-field-is-missing-in-kv-pair/113325/3 "2018-01-30T18:09:02Z")

</div>

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