user1869257 user1869257 - 5 months ago 9
JSON Question

How do I get all string values, not Keys, from a JSON using RegEx?

This is the regex I have so far but it is selecting Keys. I only want to select all occurrences of values: https://regex101.com/r/fA5cP9/1

{
"contact": {
"name": "John Doe",
"label": "Web Developer",
"email": "email@example.com",
"phone": "(123) 123-1234",
"website": "www.example.com",
"profiles": [{
"network": "LinkedIn",
"url": "www.linkedin.com"
}]
}
}

Answer

Because this is not exactly a real world problem to solve, it’s probably easiest to stick to the RegEx approach.

Your RegEx is almost correct, you just forgot one thing: the sole thing that distinguishes keys from values is the colon between the two. Each value is preceded by a colon, so you have to change the RegEx to \:\s?\"(.*?)\". The \s? makes sure it works, even if there’s a space after the colon.

Now you need to stringify the JSON, make the replacements and then re-parse it:

var resume = {
    "contact": {
        "name": "John Doe",
        "label": "Web Developer",
        "email": "email@example.com",
        "phone": "(123) 123-1234",
        "website": "www.example.com",
        "profiles": [{
            "network": "LinkedIn",
            "url": "www.linkedin.com"
        }]
    }
};

var greekedResume = JSON.parse(JSON.stringify(resume)
    .replace(/:\s?\"(.*?)\"/g, ":\"Lorem ipsum\""));
Comments