[英]How to convert an array to JSON format
I have a string array, eg 我有一个字符串数组,例如
p[]={"John","Kevin","Lex"}
I want to convert it to JSON so that the data appears in key-value pair like: 我想将其转换为JSON,以便数据以键值对的形式出现,例如:
{
"name":"John",
"name":"Kevin"
}
How can I achieve that? 我该如何实现?
First, p[]={...}
is not legal JavaScript. 首先, p[]={...}
不是合法的JavaScript。 I'll assume you meant this: 我假设您的意思是:
p = ["John","Kevin","Lex"]
Second, duplicate keys in JSON is allowed by the spec, but it is not supported by most JSON libraries. 其次,规范允许使用JSON中的重复键,但大多数JSON库均不支持。 See this question . 看到这个问题 。
This is because most languages (like the JavaScript you're using) serialize associative array structures to JSON objects. 这是因为大多数语言(例如您正在使用的JavaScript)将关联数组结构序列化为JSON对象。 Associative arrays explicitly map keys to values uniquely: 关联数组将键唯一地显式映射到值:
> a = {}
> a.name = "John"
{name: "John"}
> a.name = "Jeff"
{name: "Jeff"}
So if you try the simplest possible JSON stringification mechanism on p
or a
, you don't get what you want: 因此,如果您尝试在p
或a
上使用最简单的JSON字符串化机制,那么您将无法获得所需的结果:
> JSON.stringify(p)
'["John","Kevin","Lex"]'
> JSON.stringify(a)
'{"name":"Jeff"}'
Try this function: 试试这个功能:
var many_named_JSON = function(array_of_names) {
array_string = JSON.stringify(array_of_names.map(function (item) {
return "name:" + item;
}));
contents_regex = /\[(.*)\]/g;
return ("{" + contents_regex.exec(array_string)[1] + "}").replace(/name:/g, 'name":"');
};
Here it is working: 它在这里工作:
> many_named_JSON(["John","Kevin","Lex"])
'{"name":"john","name":"jeff"}'
You wanted something like this ? 你想要的东西,像这样 ?
var aArray = ["John","Kevin","Lex"];
var oMainObject = {};
var aMainObjectArray = [];
for (var i = 0; i < aArray.length; i++){
var oObject = {};
oObject.name = aArray[i];
aMainObjectArray.push(oObject);
)
oMainObject.data = aMainObjectArray;
As a result, oMainObject
object contains: 结果, oMainObject
对象包含:
{data: [{"name":"John"},{"name":"Kevin"},{"name":"Lex"}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.