简体   繁体   English

如何将Array对象放入JSON?

[英]How to put an Array object into JSON?

I have written the following Javascript code. 我已经编写了以下Javascript代码。 It's the best I could do to get my data formatted as valid JSON: 最好使我的数据格式化为有效JSON:

var roles = getSelectedRoles(); // returns an Array object

/* TODO: Find a better way to get the roles into my JSON data */
var rolesString = '["' + roles[0] + '"';
if (roles.length > 1)
    for (var i = 1; i < roles.length; i++)
        rolesString += ',"' + roles[i] + '"';
rolesString += ']';                        

var lid = $('#lid').val();

var json = '{ "id": "' + lid + '", "roles":' + rolesString + '}';

As you can see, I am building my JSON with string concatenation looping thru my Array object. 如您所见,我正在通过字符串对象通过Array对象循环构建JSON。 This is so ugly and it seems like there ought to be a clean way of inserting my Array data into my JSON. 这太丑陋了,似乎应该有一种将Array数据插入JSON的干净方法。

If its just inserting array object into another object then: 如果只是将数组对象插入另一个对象,则:

var selRoles = getSelectedRoles(); 
var lid = $('#lid').val();  
var json = {
 id:lid ,
 roles: selRoles
};

If you need the whole object to be represented as a String then you can use Douglas Crockford's JSON2.js to achieve the same. 如果需要将整个对象表示为String,则可以使用Douglas Crockford的JSON2.js来实现。

Include the js file mentioned above in your page and then you use: 在页面中包含上述js文件,然后使用:

var jsonString = JSON.stringify(json) //json is from previous code.

Can you try: 你能试一下吗:

<script type="text/javascript">
var jsonObj = {
    id: lid,//$('#lid').val()
    roles:roles // getSelectedRoles()
}
var jsonStr = json_encode(jsonObj);
</script>

You can find the function: json_encode at here 您可以在此处找到函数: json_encode

您可以使用角色数组的join函数:

var rolesString = '["' + roles.join('", "') + '"]';

当前的浏览器提供了JSON对象类型,可以使这种事情变得微不足道(JSON.stringify(obj))..例如,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM