how to change json key:value

93,339

Solution 1

<script>
var json = [{ "id": "5001", "type": "None" },
            { "id": "5002", "type": "Glazed" },
            { "id": "5005", "type": "Sugar" },
            { "id": "5003", "type": "Chocolate" },
            { "id": "5004", "type": "Maple" },
            { "id": "5009", "type": "Juice" }];
/**
 * The function searches over the array by certain field value,
 * and replaces occurences with the parameter provided.
 *
 * @param string field Name of the object field to compare
 * @param string oldvalue Value to compare against
 * @param string newvalue Value to replace mathes with
 */
function replaceByValue( field, oldvalue, newvalue ) {
    for( var k = 0; k < json.length; ++k ) {
        if( oldvalue == json[k][field] ) {
            json[k][field] = newvalue ;
        }
    }
    return json;
}

/**
 * Let's test
 */
console.log(json);

replaceByValue('id','5001','5010')
console.log(json);

replaceByValue('type','Chocolate','only water')
console.log(json);
</script>

Solution 2

Take a look at Pinch, a (multi) data replacement tool for JavaScript objects/JSON. Here is a brief example how pinch.js could be used in your case:

var data = [
  {
    id: 5001,
    type: 'None'
  },
  {
    id: 5002,
    type: 'Glazed'
  },
  {
    id: 5005,
    type: 'Sugar'
  },
  {
    id: 5003,
    type: 'Chocolate'
  },
  {
    id: 5004,
    type: 'Maple'
  },
  {
    id: 5009,
    type: 'Juice'
  }
];

pinch(data, '/id/', function(path, key, value) {
  return (value === 5001) ? 5010 : value;
});

Solution 3

try this. simplified.

var json = [{ "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" },
                { "id": "5009", "type": "Juice" }];           

        var JsonObject= JSON.parse(json);
            $.each(JsonObject, function(key,value) {
                if( JsonObject[key].id=='5005' ){
                    JsonObject[key].id='1234';
                }             

                if( JsonObject[key].type=='Chocolate' ){
                    JsonObject[key].type='Only water';
                }

            });

Solution 4

modified the function from above to be able to change all values of a key,and increment it by 1. And you can pass in the jsonObj

function replaceByValue( jsonObj, field, oldvalue, newvalue ) {
    for( var k = 0; k < jsonObj.length; ++k ) {
             jsonObj[k][field] = (newvalue *1)+k;

    }
    return jsonObj;
}

//example

var json = [{ "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" },
                { "id": "5009", "type": "Juice" }]; 


json; 

replaceByValue( json, "id", "na", 123 );

json;
Share:
93,339

Related videos on Youtube

NovaYear
Author by

NovaYear

I love to design, I'm dealing with about 5 years of amateur web design. I did not know there are many issues. I'm curious to new technologies. I like to design in different ways. get me interested in php, ajax, nodejs, phantomjs, as there are languages.

Updated on May 14, 2022

Comments

  • NovaYear
    NovaYear 15 days
    //my json data    
    var jsndata = "{ "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" },
                { "id": "5009", "type": "Juice" }"
    

    How would i change "type": "Chocolate" => "type": "only water"
    or.. "id": "5005" => "id": "1234"

    My list is very long.. I need get or set any value ?

    Note: My list is dynamic and always sorting order by id or type..

    Will jsndata.id['5003']='1234' change it?

    var getval = jsndata.id['5005'].type get val..(value Sugar) ?

    • Felix Kling
      Felix Kling over 11 years
      Your JSON string is not well formatted. You need [...] around the objects.
    • RMorrisey
      RMorrisey
      It looks to me like you have syntax errors in your code. You should fix it so that the quotation marks are in the right places. In the real code you're working with, are you using a string which contains the entire dataset, or are you using an object literal? It's not clear from your example.
    • St.Woland
      St.Woland
      your JSON string is not correct, cosider using different types of quotes.
    • Felix Kling
      Felix Kling
      jsndata.id['5003']='1234' is wrong syntax.
  • HattrickNZ
    HattrickNZ almost 6 years
    i get this VM159:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1(…) for var JsonObject= JSON.parse(json);
  • zero8
    zero8 over 5 years
    not in my side i have already tested it . please share a test link if you have time ( = .
  • Neophile
    Neophile over 5 years
    Brilliant answer. Spot On! Thanks.
  • zero_cool
    zero_cool over 5 years
    Awesome method name for this functionality.
  • Zain Aftab
    Zain Aftab over 4 years
    can it also change the datatype of value like if I want to change {"abc":123} to {"abc":[]} can it be done by your code?