Append JSON Strings

append, concatenation, jquery, json, string

Solution

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

Problem

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?

Original source