1

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?

Dijkgraaf
  • 11,049
  • 17
  • 42
  • 54
Rakeh Sahu
  • 47
  • 3
  • 11

2 Answers2

0

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"}'
Community
  • 1
  • 1
kdbanman
  • 10,161
  • 10
  • 46
  • 78
-1

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"}]}
keshet
  • 1,716
  • 5
  • 27
  • 54
  • Probably not, seeing as your output and his output are completely different. – kdbanman Jun 26 '15 at 19:57
  • If I understand correctly, he wants to use the json object as a source for a json model. Else, there is a little sense in the object he showed in his question. Of course, I may be wrong. – keshet Jun 26 '15 at 20:00
  • He wants `'{ "name":"John", "name":"Kevin" }'`. You gave `'[{"name":"John"},{"name":"Kevin"},{"name":"Lex"}]'`. – kdbanman Jun 26 '15 at 20:20
  • 2
    Please include your code in your answer, and not just a link to it. Thanks! – Wally Altman Jun 26 '15 at 22:22