从一个json对象动态添加数据到另一个json对象

时间:2012-06-18 07:36:04

标签: javascript jquery json dynamically-generated

假设我有一个json对象的朋友:

{
   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"
   }
   ]
}

将其存储为文件friends.json

现在使用javascript / jQuery,我需要创建一个新对象good_friends.json,并需要使用“people.id”从friends.json的“people”字段添加值(DYNAMICALLY和逐个) ”。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

如果您想保存更改,则几乎需要服务器端进程。

您可以通过ajax加载JSON:

$.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
    }
});

要添加到反序列化对象,只需在内存中修改它:

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

当然,这些值可能来自输入字段或其他内容,例如:

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

现在您拥有数据的内存副本。要在某处存储,您必须有一个服务器端进程,您可以将其发布到。您可能会在发布之前对其进行序列化,例如,通过JSON.stringify或类似方式。如果您的浏览器本身没有JSON.stringify(大多数现代浏览器都没有),那么您可以使用Crockford's

或者,如果这仅供您自己使用,您可以在文本字段中显示字符串化结果,并使用复制粘贴将其粘贴到文本编辑器中的friends.json

这是一个完整的示例,它在文本区域中显示JSON: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>