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?
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.
We can merge two JSON objects using the putAll() method (inherited from interface 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.
// 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 );
{
"name": "John",
"myData": "Hello World",
"myAnotherData": "FooBar"
}
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.
MDN documentation
Browser support
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With