I have a "json" like this:
{
example:"hi there",
dateTime: "01/01/1970 bla:bla"
}
I should replace all the value before the colon wrapping them inside a doublequote.
Referring to this response Regex in ruby to enclose word before : with double quotes, I tried the code, but was not yet full correct, because it changed also the value before the colon in the dateTime.
so I should add to this code
(\w+)(?=:)
another control, which sees if the word is just after a comma.
I would like to change, so, the "json" to a real json like this:
{
"example":"hi there",
"dateTime": "01/01/1970 bla:bla"
}
and not like this like now:
{
"example":"hi there",
"dateTime": "01/01/1970 "bla":bla"
}
Here is the solution to select all attributes and replace(Check the demo):
For all case alphabets:
/(?:[a-z]+(?=:[" ]))/ig
For alphanumeric and underscore:
/(?:[\w]+(?=:[" ]))/g
Demo:
https://www.regextester.com/?fam=107535
?: is used to create group without back referencing. Hence, increases computational speed as it doesn't have to remember the group for reuse.
If you can rely to the position of values to be replaced at the start of the line, as in your example, you can use a regex like ^ +([a-zA-Z0-9_]*):, that matches only sequences of alphanumerical characters and underscores before colon and preceded by zero or more spaces and captures the sequence as first group.
You can see using online regex validator what is matched/captured and what is not for the input sample you showed.
Then you can use the captured group to wrap the text you are interested on in double quotes.
Simple runnable example in JS:
var input = `{
example:"hi there",
dateTime: "01/01/1970 bla:bla"
}`
var regexp = /^[ \t]+([a-zA-Z0-9_]*):/mg
var replaced = input.replace(regexp, '"$1":')
console.log(replaced)
EXPLANATION: m flag enables multiline match, g flag enables match all mode
I can't show you a Ruby example but the provided regexpr should help you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With