-5

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?

3
  • That JSON is invalid in a couple of ways. The keys need to be in double quotes, as do all other strings (such as Friends and /friends.json). See json.org and jsonlint.com. Commented Jun 18, 2012 at 7:39
  • Simply make javascript objects from your JSON strings using JSON.parse and make basic javascript operations on your objects. Commented Jun 18, 2012 at 7:40
  • I'm quite new to jQuery and json, so don't have much knowledge about them. I can't seem to think of anything that why i've posted this question. It may be a bit dumb but any help will be greatly appreciated. Commented Jun 18, 2012 at 7:49

1 Answer 1

2

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:

$.ajax({
    url: "/path/to/friends.json",
    dataType: "json",
    success: function(data) {
        // Here, `data` will be the object resulting from deserializing the JSON
        // Store `data` somewhere useful, perhaps you might have a `friends`
        // variable declared somewhere; if so:
        friends = data;
    },
    error: function() {
       // Handle the error
    }
});

To add to the deserialized object, you just modify it in memory:

friends.people.push({
    id: String(friends.people.length + 1),
    name: "John",
    img: "img/john.jpg"
});

Of course, those values will probably come from input fields or something, e.g.:

function addPerson() {
    friends.people.push({
        id: String(friends.people.length + 1),
        name: $("#nameField").val(),
        img: $("#imgField").val()
    });
}

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.stringify or similar. If your browser doesn't have JSON.stringify natively (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.json in a text editor.

Here's a complete example, which shows the JSON in a text area: Live copy | source

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test Page</title>
<style>
  body {
    font-family: sans-serif;
  }
</style>
</head>
<body>
  <label>Name:
    <input type="text" id="nameField">
  </label>
  <br><label>Img:
    <input type="text" id="imgField">
  </label>
  <br><input type="button" id="btnAdd" value="Add" disabled>
  <input type="button" id="btnShow" value="Show JSON" disabled>
  <br><div id="msg">&nbsp;</div>
  <hr>
  <textarea id="showField" rows="10" cols="60"></textarea>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
// Note that all of our script tags are at the end of the
// document. This lets the page load as quickly as possible
// and means we don't have to worry about whether the elements
// have been created yet (they have, because the scripts are
// below them).

// Put all of our code inside a function so we don't
// create globals
(function($) {
    if (typeof JSON === "undefined") {
        // Load Crockford's json2.js
        // NOTE: You'd want to use your own copy, not a hotlink
        // to his github like this.
        var scr = document.createElement('script');
        scr.src = "https://raw.github.com/douglascrockford/JSON-js/master/json2.js";
        document.documentElement.appendChild(scr);
    }

    var friends; // Where our deserialized friends.json will go

    // Focus the first field
    $("#nameField").focus();

    // Load the JSON
    $.ajax({
        url: "http://jsbin.com/ojexuz",
        dataType: "json",
        success: function(data) {
            // Here, `data` will be the object resulting from deserializing the JSON
            // Store `data` somewhere useful, perhaps you might have a `friends`
            // variable declared somewhere; if so:
            friends = data;

            // Enable our buttons now that we have data
            $("input[type='button']").prop("disabled", "");
        },
        error: function() {
            // Handle the error
            alert("Error loading friends.json");
        }
    });

    // Handle clicks on the "Add" button
    $("#btnAdd").click(function() {
        var nameField = $("#nameField"),
            imgField  = $("#imgField"),
            name      = $.trim(nameField.val()),
            img       = $.trim(imgField.val());
        if (!name || !img) {
            alert("Please supply both name and image");
            return;
        }
        addPerson(name, img);
        $("#msg").text("Added '" + name + "'");
        nameField.focus();
    });

    // An "add this person" function
    function addPerson(name, img) {
        friends.people.push({
            id:   String(friends.people.length + 1),
            name: name,
            img:  img
        });
    }

    // Handle clicks on the "Show" button
    $("#btnShow").click(function() {
        $("#showField").val(JSON.stringify(friends));
    });

})(jQuery);
</script>
</body>
</html>
Sign up to request clarification or add additional context in comments.

5 Comments

Very nicely done, the live copy & code will be very useful for any starter looking up JSON/Ajax examples.
Thanks! That's a lot of valuable info... However, i needed to create a NEW json object and add values to it. How can i do that?
@VJ41: You probably don't mean "JSON object." You probably just mean "object." (JSON is a textual notation used for exchanging data; once you're interacting with the data in code, you're no longer using JSON, just objects.) To create an object, you use an object initializer, {}, optionally with properties in it. I've used one above in addPerson. For instance, var o = {foo: "bar"}; creates an object with one property, foo, whose value is "bar", and assigns that object to the variable o.
I need to send the new data to server for further processing. Will i need json object for that?
@VJ41: Typically you send data to the server in name/value pairs. For complex, structured data, sending a name/value pair where the value is an object graph serialized to JSON is a great way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.