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

1
  • What property names would you want? It doesn't make sense to try to convert a JavaScript array into a JSON object. Commented Apr 25, 2014 at 11:46

3 Answers 3

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}));
Sign up to request clarification or add additional context in comments.

3 Comments

The question is asking to convert the array to a JSON object, not one of the objects inside it.
He requested to start with {}.
Indeed. The question doesn't make sense. I don't think it is answerable in its current state.
2

Like this:

JSON.stringify(me.reduce(function(o, v, i) {
    o[i] = v;
    return o;
}, {}));

4 Comments

That won't work. That will give you a JSON array, not an object.
After editing, it converts one of the objects in the array to a JSON object instead of converting the array to one.
That now does what the question is asking. The requirement is still bizarre though.
True that... Really dunno why the OP needs this kind of black magic.
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);

2 Comments

That won't work. That will give you a JSON array, not an object.
yaa you right @Quentin

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.