-5

假设我有一个 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”字段中添加值(动态和一对一)。我怎样才能做到这一点?

4

1 回答 1

2

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

您可以通过以下方式加载 JSON 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
    }
});

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

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 的.

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

这是一个完整的示例,它在文本区域中显示 JSON:Live copy | 资源

<!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>
于 2012-06-18T07:47:44.760 回答