将js变量插入json对象

时间:2014-07-25 10:13:19

标签: javascript json

我有一个名为list_to_book_for的有效json对象:

{"fold1-key1":{"name":"Van Antwerpen"},"fold2-key2":{"name":"Delporte"},"fold3-key3":{"name":"Lallemand"}}

我想在此对象中添加变量的内容:

"fold1":
    {
        "name": "Too book for ",
        "items":
        {

        }
    },

我想将变量插入到项目中吗?

6 个答案:

答案 0 :(得分:0)

当然可以

var x = 'your items';

var obj = { fold1: { name: "Too book for ", items: {} } };

obj.fold1.items = x;

答案 1 :(得分:0)

当然:

var jsonObj = {"fold1": {
    "name": "Too book for ", 
    "items": {} 
}}; // or do JSON.parse on your original json
var items = {"fold1-key1":{"name":"Van Antwerpen"},"fold2-key2":{"name":"Delporte"},"fold3-key3":{"name":"Lallemand"}};

jsonObj.fold1.items = items;
var result = JSON.stringify(jsonObj); 

将返回:

{"fold1":
    {"name":"Too book for ",
     "items":
         {"fold1-key1":{"name":"Van Antwerpen"},
          "fold2-key2":{"name":"Delporte"},
          "fold3-key3":{"name":"Lallemand"}
          }
    }
}

答案 2 :(得分:0)

也许这就是你想要做的事情:

for( var key in list_to_book_for ) {
  if( list_to_book_for.hasOwnProperty(key) ){
     obj.fold1.items[key] = list_to_book_for[key];
  }
}

答案 3 :(得分:0)

如果您的JSON对象仍然采用原始JSON格式,请执行以下操作:

list_to_book_for = '{"fold1-key1":{"name":"Van Antwerpen"},"fold2-key2":{"name":"Delporte"},"fold3-key3":{"name":"Lallemand"}}';

然后,您可以使用JSON.parse()

将JSON解析为javascript
"fold1": {
    "name": "To book for ",
    "items": JSON.parse(list_to_book_for)
},

答案 4 :(得分:0)

谢谢大家的帮助,这是解决方案

我在代码的顶部声明了一个全局变量:

    chaine_book_for = {};

    chaine_book_for = function()
    {
        var tmp;
        $.ajax(
        {
            method:'POST',
            dataType: 'json',
            async: false,
            url:'ajax/liste_users.php',
                                                                                    success:function(retour_php)
    {
                                                                                                                chaine_book_for = retour_php;
                                                                                                                tmp = retour_php;
    }
});
return tmp;
}();

重要的是将 async:false

我在子菜单(json对象)中插入内容:

"fold1":
{
    "name": "Too book for ",
    "items": chaine_book_for,
    callback: function(key, options)

答案 5 :(得分:-1)

尝试使用eval,对于此代码工作正常,请查看

 <script>
var obj={"fold1-key1":{"name":"Van Antwerpen"},"fold2-key2":{"name":"Delporte"},"fold3-key3":{"name":"Lallemand"}};
var s='{"fold1": {"name": "Too book for ","items": { } }}';
eval('var u='+s);
for(x in u)
{
    obj[x]=u[x];
}
</script>