Add JSON Strings

I am having problems with some JS and hope someone can help.

I have two JSON strings that are assembled through AJAX using jQuery and then parsed accordingly. The problem is that if I ever want to add new functions to the application I create, the JSON strings are statically stored in the database and will not change if new attributes are added to the default JSON string.

var string1 = {
    "col1": [
        {
            "foo": "bar"
        }
    ],
    "col2": [
        {
            "foo": "bar",
            "bar": "foo"
        }
    ],
    "col3": [
        {
            "foo": "bar"
        }
    ]
}

var string2 = {
    "col1": [
        {
            "foo": "bar"
        }
    ],
    "col2": [
        {
            "foo": "bar"
        }
    ]
}

string2the user saved a script hypothetically saved three days ago. Since then, the default row has been added string1, and information should be added to string2.

Can anyone help with this?

+3
source share
2 answers

This will do:

// Input:
var json_string = '{"name":"John"}';

// Convert JSON array to JavaScript object
var json_obj = JSON.parse( json_string );

// Add new key value pair "myData": "Helo World" to object
json_obj.myData = 'Hello World';

// Another more dynamic way to add new key/value pair
json_obj['myAnotherData'] = 'FooBar';

// Convert back to JSON string
json_string = JSON.stringify( json_obj );

// Log to console:
console.log( json_string );

Conclusion:

{
    "name": "John",
    "myData": "Hello World",
    "myAnotherData": "FooBar"
}

jQuery JSON parser:

jQuery IE7,

var json_obj = JSON.parse( json_string );

var json_obj = $.parseJSON( json_string );

, jQuery json_object JSON, .

:

MDN

+12

, :

function updateJsonString(oldString, newString) {
    var oldObj = JSON.parse(oldString), newObj = newString.parse(newString);
    for(prop in newObj) {
        if(newObj.hasOwnProp(prop)) {
            if(!oldObj.hasOwnProp(prop)) {
                oldObj[prop] = newObj[prop];
            }
        }
    }

    return JSON.stringify(oldObj);
}

var updatedString = updateJsonString(string2, string1);
0

All Articles