将顶级JSON添加到Javascript对象

时间:2014-09-11 08:21:12

标签: javascript json

有没有人知道如何将顶级json附加到现有对象?

这就是我所拥有的:

   var url = "http://domain.com/gettxt";
        $.ajax({
            url: url,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                rootData = data;
                renderView();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert("error" + errorThrown)
            }
        });

此时,数据包含以下内容:

   [{"id":1,"title":"Johnson"}]

我需要它像这样:

   { "record": [ {"id":1}, {"title":"Johnson"} ] }

换句话说:

   rootData = "{ "record":" + data + "}";

有谁知道我怎么能做到这一点?不幸的是,在Javascript之前添加顶级版本不是一个选项,谢谢。

4 个答案:

答案 0 :(得分:2)

您可以使用对象文字来执行此操作:

rootData = { record: data };

所以你的代码看起来像这样:

 success: function (data, textStatus, jqXHR) {
     rootData = { record: data };
     renderView();
 },

答案 1 :(得分:2)

你可以直接添加这样的对象类型,

rootData = { record: data };

您的最终代码将是

var url = "http://domain.com/gettxt";
    $.ajax({
        url: url,
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            rootData = { record: data };
            renderView();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("error" + errorThrown)
        }
    });

答案 2 :(得分:1)

试试这个

var arr = [{"id":1,"title":"Johnson"}];
var obj ={};
obj.record = arr;
console.log(obj);

答案 3 :(得分:1)

a = [{"id":1,"title":"Johnson"}]
root = {record: a}
相关问题