javascript 如何使用javascript创建以下类型的json数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15356510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create the following type of json array using javascript?
提问by Jetson John
How to create the following type of json array using javascript?
如何使用javascript创建以下类型的json数组?
xAxis: {
categories: [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
}
回答by T.J. Crowder
Well, you have two options:
那么,你有两个选择:
Create the array and then stringify it:
var categories = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; var json = JSON.stringify(categories);
JSON.stringify
exists on most modern browsers, and you can shim it. (There are several shims available, not least from Crockford's github page-- Crockford being the person who defined JSON.)Or just create the JSON string directly:
var json = '["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]';
创建数组,然后将其字符串化:
var categories = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; var json = JSON.stringify(categories);
JSON.stringify
存在于大多数现代浏览器中,您可以填充它。(有几个垫片可用,尤其是来自Crockford 的 github 页面——Crockford 是定义 JSON 的人。)或者直接创建 JSON 字符串:
var json = '["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]';
Re your edit: That's not "an array" anymore, it's an object with an array in it (or an object with an object in it with an array in that). It doesn't fundmentally change the answer, though:
回复您的编辑:这不是“数组”了,这是在一个数组(或在它的对象与数组中的对象的对象是)。不过,它并没有从根本上改变答案:
var xAxis = { categories: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] };
var json = JSON.stringify(xAxis);
or
或者
var json = '{"categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]}';
I wasn't sure whether you wanted the xAxis
layer in there. If so, it's just another layer around the above, e.g.:
我不确定你是否想要xAxis
那里的图层。如果是这样,它只是上面的另一层,例如:
var obj = { xAxis: { categories: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] } };
var json = JSON.stringify(obj);
or
或者
var json = '{"xAxis": {"categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]}}';
More about JSON on the JSON home page. Fundamentally, all strings must be in double (not single) quotes, and all property names must be in double quotes.
有关 JSON 的更多信息,请访问 JSON 主页。从根本上说,所有字符串都必须用双(不是单)引号引起来,并且所有属性名称都必须用双引号引起来。