'Javascript Regex to match value of JSON key value pair
Given the following key value pairs, how could I match just the values (including the quotes)?
Explanation: I'm doing a find and replace in my IDE. I have hundreds of key/value pairs where the values need to be changed from strings to objects. So basically replacing the value.
"ElevationFilenameIn": "Input raster elevation file",
"TargetCRS": "Target vertical coordinate reference system Type",
"featureName": "The name of the feature to extract, for example \"Vegetation\" or \"Water\"",
"TargetCRScode": "Target vertical coordinate system Code",
"TargetCRSfile": "The projection (.prj) file in shoebox to be used for this inputfile"
My attempt (which is not working, not even close):
[:]\s*(\"\w*\")
Solution 1:[1]
You can use the pattern:
[:]\s(\".*\")
and test it following this link: https://regex101.com/r/nE5eV3/1
Solution 2:[2]
I guess this one does the job also well. One good part it doesn't use any capture groups one bad part it's more costly compared to the accepted answer.
[^:]+(?=,|$)
Solution 3:[3]
Get value
[^:"]+(?="})
Get value by key
If you wish to select a specific key that can be done like so:
[^:KEY"]+(?="})
Solution 4:[4]
All key value par in complex JSON object.
"[a-zA-Z0-9 -]*"(?=:):[a-zA-Z0-9 "-?]*(?<=")|"[a-zA-Z0-9 -]*"(?=:):[a-zA-Z0-9 "-?]*(?=,)|"[a-zA-Z0-9 -]*"(?=:):[a-zA-Z0-9 "-?]*(?=\w+)
Solution 5:[5]
To get a value by itself without capturing the key:
(?:\"keyname)(?:\"\s?:\s?\")(.*)(?:\")
For example given:
{"keyname":"value"}
This will capture
value
Test here: https://regex101.com/r/Bm1mmK/1
Solution 6:[6]
Here's one that works when the value is another json object:
:\s*["{](.*)["}]\s*[,}]
It does not include the quotes/brackets in the capture group. If you want to include those, the capture group is easily modified:
:\s*(["{].*["}])\s*[,}]
The expressions also handle varying whitespace since json ignores whitespace.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | demartis |
Solution 2 | Redu |
Solution 3 | |
Solution 4 | Pavle Nožini? |
Solution 5 | Akumaburn |
Solution 6 | Aaron Gibby |