如何將數組轉換為JSON格式

[英]How to convert an array to JSON format


I have a string array, e.g.

我有一個字符串數組,例如

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?

我怎樣才能做到這一點?

2 个解决方案

#1


First, p[]={...} is not legal JavaScript. I'll assume you meant this:

首先,p [] = {...}不是合法的JavaScript。我猜你的意思是:

p = ["John","Kevin","Lex"]

Second, duplicate keys in JSON is allowed by the spec, but it is not supported by most JSON libraries. See this question.

其次,規范允許使用JSON中的重復鍵,但大多數JSON庫都不支持它。看到這個問題。

This is because most languages (like the JavaScript you're using) serialize associative array structures to JSON objects. Associative arrays explicitly map keys to values uniquely:

這是因為大多數語言(如您正在使用的JavaScript)將關聯數組結構序列化為JSON對象。關聯數組顯式地將鍵唯一地映射到值:

> 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"}'

#2


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"}]}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/05/06/72fe6e58dcc43b404df8b361f8c30ee3.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com