将数据从一个json对象动态添加到另一个 [英] Adding data dynamically from one json object to another

查看:125
本文介绍了将数据从一个json对象动态添加到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

此文件存储为文件friends.json

This is stored as a file friends.json

现在使用javascript/jQuery,我需要创建一个新对象good_friends.json,并需要使用"people.id"从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.

您可以通过ajax加载JSON:

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()
    });
}

现在,您有了数据的内存中副本.要存储在某个地方,您必须有一个服务器端进程可以将其发布到该进程.您可能会在发布之前将其序列化,例如通过JSON.stringify或类似名称.如果您的浏览器本身没有JSON.stringify(大多数现代浏览器没有,有些则没有),则可以使用克罗福德的.

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.

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

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.

这是一个完整的示例,它在文本区域中显示JSON:实时复制 |

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>

这篇关于将数据从一个json对象动态添加到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆