Suppose i have a json object friends as:
{
title: Friends
link: /friends.json
description: "My friends"
people: [
{
id: "1",
name: "Matthew",
img: "img/matthew.jpg"
},
{
id: "2",
name:"Matt",
img: "img/matt.jpg"
},
{
id: "3",
name: "David",
img: "img/dav.jpg"
}
]
}
This is stored as a file friends.json
Now using javascript/jQuery, i need to create a new object good_friends.json and need to add values (DYNAMICALLY and one-by-one) to it from “people” field of friends.json using the “people.id”. How can i do that?
You’re pretty much going to need a server-side process if you want to save your changes.
You can load the JSON via
ajax:To add to the deserialized object, you just modify it in memory:
Of course, those values will probably come from input fields or something, e.g.:
Now you have an in-memory copy of your data. To store it somewhere, you have to have a server-side process you can post it to. You’d probably serialize it before posting, e.g., via
JSON.stringifyor similar. If your browser doesn’t haveJSON.stringifynatively (most modern ones do, some older ones don’t), you can use Crockford’s.Or if this is just for your own use, you could display the stringified result in a text field and the use copy-and-paste to paste it into
friends.jsonin a text editor.Here’s a complete example, which shows the JSON in a text area: Live copy | source