Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append JSON Strings

I'm having a little trouble with some JS and hope someone can help.

I have two JSON strings that are collected via AJAX using jQuery and then parsed accordingly. The issue I have is that if I ever want to add new features to the application I am making, the JSON strings are statically stored in the database and don't 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"
        }
    ]
}

string2 is the user saved the script, hypothetically saved three days ago. Since then, the default string string1 has been added to, and the information needs to be added to string2.

Can anyone help with this?

like image 671
mbark Avatar asked May 07 '12 21:05

mbark


People also ask

How do I append to a JSON object?

Steps for Appending to a JSON FileRead the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.

How do I combine two JSON responses?

We can merge two JSON objects using the putAll() method (inherited from interface java.

How do you add to a JSON object in Java?

Log. i(AppHelper. APP_LOG_NAMESPACE, "POSITIONS AVAILABLE " + jsonDataString); AppHelper helper = new AppHelper(ctx); JSONObject mainObject = new JSONObject(jsonDataString); JSONObject valuesObject = new JSONObject(); JSONArray list = new JSONArray(); //putv given values to the JSON valuesObject. put("lat", lat.


1 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 );

Output:

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

jQuery JSON parser:

If you want to use jQuery parser or need support for IE7 you can replace

var json_obj = JSON.parse( json_string );

with

var json_obj = $.parseJSON( json_string );

Unfortunately, jQuery cannot convert json_object back to JSON string, you will need another plugin or library for that.

More on topic:

MDN documentation

Browser support

like image 133
Sampo Sarrala - codidact.org Avatar answered Sep 22 '22 17:09

Sampo Sarrala - codidact.org