skip to Main Content

i want to replace 11111 to <, and 22222 to > in json

My code:

var json_A = {
  "question1": {
    "type": "string",
    "title": "11111img src=`https://i.imgur.com/RQpTQBw.png`22222",
    "enum": ["Adrian", "Attams", "Adrienne"],
    "requested": false
  },
  "question2": {
    "type": "string",
    "title": "11111img src=`https://i.imgur.com/SHB02L8.png`22222",
    "enum": ["She does.", "No.", "Yes"],
    "requested": false
  }
}


function replaceValueOfJson(json, field, oldvalue, newvalue) {
  for (var k = 0; k < json.length; ++k) {
    if (oldvalue == json[k][field]) {
      json[k][field] = newvalue;
    }
  }
  return json;
}

var string_format = replaceValueOfJson(json_A,'title','11111','aaaaa')
//alert(string_format)
console.log(string_format)

My desired output:

{
  "question1": {
    "type": "string",
    "title": "<img src=`https://i.imgur.com/RQpTQBw.png`>",
    "enum": ["Adrian", "Attams", "Adrienne"],
    "requested": false
  },
  "question2": {
    "type": "string",
    "title": "<img src=`https://i.imgur.com/SHB02L8.png`>",
    "enum": ["She does.", "No.", "Yes"],
    "requested": false
  }
}

Related topic: how to change json key:value

How can i change above function to get correct output?

My link: https://jsfiddle.net/bvotcode/y5gs9jwp/28/

4

Answers


  1. JavaScript objects don’t have a length property. (Unless you manually add one)

    Instead, you can iterate over Object.values() and execute String#replace() on the field of your choice like this:

    var json_A = {
      "question1": {
        "type": "string",
        "title": "11111img src=`https://i.imgur.com/RQpTQBw.png`22222",
        "enum": ["Adrian", "Attams", "Adrienne"],
        "requested": false
      },
      "question2": {
        "type": "string",
        "title": "11111img src=`https://i.imgur.com/SHB02L8.png`22222",
        "enum": ["She does.", "No.", "Yes"],
        "requested": false
      }
    }
    
    
    function replaceValueOfJson(json, field, oldvalue, newvalue) {
      for (let obj of Object.values(json)) {
        obj[field] = obj[field].replace(oldvalue, newvalue);
      }
      return json; // This isn't really necessary as this will modify the object passed to it in-place
    }
    
    replaceValueOfJson(json_A,'title','11111','<');
    replaceValueOfJson(json_A,'title','22222','>');
    
    console.log(json_A)

    Object.values() returns an array of the values in the object passed through it.

    Login or Signup to reply.
  2. Just indent json and you’ll see the problem:

    var json_A =
        { 
            "question1": {
                "type":"string",
                "title":"11111img src=`https://i.imgur.com/RQpTQBw.png`22222",
                "enum":["Adrian","Attams","Adrienne"],
                "requested":false },
            "question2":{
                "type":"string",
                "title":"11111img src=`https://i.imgur.com/SHB02L8.png`22222",
                "enum":["She does.","No.","Yes"],
                "requested":false }
        }
    

    Still don’t see it ? here:

    var json_A ={"question1":{"type":"string","title":"11111img src=`https://i.imgur.com/RQpTQBw.png`22222","enum":["Adrian","Attams","Adrienne"],"requested":false},"question2":{"type":"string","title":"11111img src=`https://i.imgur.com/SHB02L8.png`22222","enum":["She does.","No.","Yes"],"requested":false}}
    
    Object.keys(json_A).forEach(question=>{
        json_A[question].title = json_A[question].title.replace('11111','<');
        json_A[question].title = json_A[question].title.replace('22222','>');
    });
    
    console.log(json_A)

    Linear iterating an hierarchical structure won’t do any good. You have to consider json levels.

    Login or Signup to reply.
  3. JSON.parse((JSON.stringify(json_A)).replaceAll('11111', '<').replaceAll('22222', '>'));
    
    Login or Signup to reply.
  4. Recursive solution (will modify the original object):

    function replaceValueInJSON(object, keyToChange, callback) {
        if (keyToChange in object) {
            // If object has the given key, run callback on the corresponding value
            object[keyToChange] = callback(object[keyToChange]);
        }
        for (const [key, value] of Object.entries(object)) {
            // Recursively check in non-array object children which has not been processed.
            if (
                key !== keyToChange &&
                value instanceof Object && !(value instanceof Array)
            ) {
                replaceValueInJSON(value, keyToChange, callback);
            }
        }
    }
    

    Try it:

    function replaceValueInJSON(object, keyToChange, callback) {
      if (keyToChange in object) {
        object[keyToChange] = callback(object[keyToChange]);
      }
      for (const [key, value] of Object.entries(object)) {
        if (
          key !== keyToChange &&
          value instanceof Object && !(value instanceof Array)
        ) {
          replaceValueInJSON(value, keyToChange, callback);
        }
      }
    }
    
    const objectToChange = {
      question1: {
        type: 'string',
        title: '11111img src=`https://i.imgur.com/RQpTQBw.png`22222',
        enum: ['Adrian', 'Attams', 'Adrienne'],
        requested: false
      },
      question2: {
        type: 'string',
        title: '11111img src=`https://i.imgur.com/SHB02L8.png`22222',
        enum: ['She does.', 'No.', 'Yes'],
        requested: false
      }
    };
    
    replaceValueInJSON(objectToChange, 'title', oldValue => {
      return oldValue.replaceAll('11111', '<').replaceAll('22222', '>');
    });
    
    console.log(objectToChange);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search