bflemi3
bflemi3

Reputation: 6790

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*\")

Upvotes: 13

Views: 47585

Answers (6)

Akumaburn
Akumaburn

Reputation: 660

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

Upvotes: 1

Aaron Gibby
Aaron Gibby

Reputation: 1

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.

Upvotes: 0

Pavle Nožinić
Pavle Nožinić

Reputation: 21

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+)

Upvotes: 2

Jesse de gans
Jesse de gans

Reputation: 1654

Get value

[^:"]+(?="})

enter image description here

Get value by key

If you wish to select a specific key that can be done like so:

[^:KEY"]+(?="})

enter image description here

Upvotes: 2

Redu
Redu

Reputation: 26161

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.

[^:]+(?=,|$)

Regular expression visualization

Debuggex Demo

Regex101 Demo

Upvotes: 8

demartis
demartis

Reputation: 319

You can use the pattern:

[:]\s(\".*\")

and test it following this link: https://regex101.com/r/nE5eV3/1

Upvotes: 13

Related Questions