简体   繁体   中英

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:

{
    "name":"John",       
    "name":"Kevin"
}

How can I achieve that?

First, p[]={...} is not legal 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. See this question .

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:

> 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:

> 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:

{data: [{"name":"John"},{"name":"Kevin"},{"name":"Lex"}]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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