Search code examples
jsonregexregexp-replace

Replace whitespace in JSON keys with regex


Hi I am trying to use regex to replace spaces in heys so a json like

{"december 25":"ho ho ho", "all I want": "christmas", "ids":["sandy","claws"]}

transforms to

{"december_25":"ho ho ho", "all_I_want": "christmas", "ids":["sandy","claws"]}

I looked into this: Replace JSON key with Regex

but I didn't find a way to tweak it to replace spaces instead of a character.

Thank you!


Solution

  • You can use this regex which targets space present only in keys,

    \s(?=[^,"]*"\s*:)
    

    Demo

    Javascript demo,

    s = '{"december 25":"ho ho ho", "all I want": "christmas", "ids":["sandy","claws"]}';
    console.log('Before:', s);
    console.log('After:', s.replace(/\s(?=[^,"]*"\s*:)/g, '_'));