-2

So I have an array that looks like this:

var me = [
    {'we':'me','see':'tree','lee':'bee'},
    {'we':'me','see':'tree','lee':'bee'},
    {'we':'me','see':'tree','lee':'bee'},
    {'we':'me','see':'tree','lee':'bee'}
];

How do I convert this to a JSON object starting with '{' and ending with '}'

Xiddoc
  • 3,369
  • 3
  • 11
  • 37
Salman
  • 76
  • 1
  • 5
  • What property names would you want? It doesn't make sense to try to convert a JavaScript array into a JSON object. – Quentin Apr 25 '14 at 11:46

3 Answers3

3

With JSON.stringify?

var me =[
    {'we':'me','see':'tree','lee':'bee'},
    {'we':'me','see':'tree','lee':'bee'},
    {'we':'me','see':'tree','lee':'bee'},
    {'we':'me','see':'tree','lee':'bee'}
];

console.log(JSON.stringify(me));    // returns whole JSON.
console.log(JSON.stringify(me[0])); // returns what you want, 'starting with {}'.

//    if you want to start with {} with all data:
console.log(JSON.stringify({me:me}));
Kai
  • 1,156
  • 8
  • 18
2

Like this:

JSON.stringify(me.reduce(function(o, v, i) {
    o[i] = v;
    return o;
}, {}));
Xiddoc
  • 3,369
  • 3
  • 11
  • 37
Klemen Tusar
  • 9,261
  • 4
  • 31
  • 28
0
var myJsonString = JSON.stringify(me);

UPDATED

var me =[
{'we':'me','see':'tree','lee':'bee'},
{'we':'me','see':'tree','lee':'bee'},
{'we':'me','see':'tree','lee':'bee'},
{'we':'me','see':'tree','lee':'bee'}
];


var myjson={'list':""}
myjson.list=me;
var myJsonString = JSON.stringify(myjson);
console.log(myJsonString);
Tuhin
  • 3,335
  • 2
  • 16
  • 27