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:
{
"name":"John",
"name":"Kevin"
}
How can I achieve that?
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:
{
"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"}]}