skip to Main Content

I have a large JSON file where I want to find and replace all properies with the same string

How the JSON currently looks

{
 "example1": "some text1"
 "example2": "some text2"
 "example3": "some text3"
}

Ideal output for the JSON

{
 "example1": "hello"
 "example2": "hello"
 "example3": "hello"
}

3

Answers


  1. Chosen as BEST ANSWER

    ChatGPT helped me!

    regular expression in VSCODE is (?<=":)s*".*?"


  2. To replace all values in your JSON file with the string "hello", you can use a simple script in JavaScript.

    const fs = require('fs');
    
    const jsonString = fs.readFileSync('yourfile.json', 'utf-8');
    
    let jsonObject = JSON.parse(jsonString);
    
    for (let key in jsonObject) {
        if (jsonObject.hasOwnProperty(key)) {
            jsonObject[key] = "hello";
        }
    }
    
    const newJsonString = JSON.stringify(jsonObject, null, 2);
    
    fs.writeFileSync('yourfile.json', newJsonString);
    
    Login or Signup to reply.
  3. This is a simple task for jq. The following jq script produces the expected output:

    with_entries(.value = "hello")
    

    See it online.

    Install jq, then run this command in a terminal:

    $ jq 'with_entries(.value = "hello")' input.json > output.json
    

    … to process the JSON stored in the file input.json and save the output in the file output.json.

    The output will be formatted on multiple lines (and you can open output.json and inspect it in VSCode or another editor). If you need the output on a single line (to save space), add option -c to the jq command line:

    $ jq -c 'with_entries(.value = "hello")' input.json > output.json
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search