Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding Javascript Object to Json string

I want to encode a Javascript object into a JSON string and I am having considerable difficulties.

The Object looks something like this

new_tweets[k]['tweet_id'] = 98745521; new_tweets[k]['user_id'] = 54875;        new_tweets[k]['data']['in_reply_to_screen_name'] = "other_user"; new_tweets[k]['data']['text'] = "tweet text"; 

I want to get this into a JSON string to put it into an ajax request.

{'k':{'tweet_id':98745521,'user_id':54875, 'data':{...}}} 

you get the picture. No matter what I do, it just doesn't work. All the JSON encoders like json2 and such produce

[] 

Well, that does not help me. Basically I would like to have something like the php encodejson function.

like image 435
Lukas Oppermann Avatar asked Jul 24 '11 22:07

Lukas Oppermann


People also ask

How would you convert an object to JSON in JavaScript?

Answer: Use the JSON. stringify() Method You can use the JSON. stringify() method to easily convert a JavaScript object a JSON string.

Can we convert string to JSON in JavaScript?

String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.

Which code will convert a JavaScript object into valid JSON?

If you want to convert your JS object to a JSON string, you'll need to use the stringify method on JavaScript's native JSON object. This will encode the object to a string in both the web browser and Node. js.


1 Answers

Unless the variable k is defined, that's probably what's causing your trouble. Something like this will do what you want:

var new_tweets = { };  new_tweets.k = { };  new_tweets.k.tweet_id = 98745521; new_tweets.k.user_id = 54875;  new_tweets.k.data = { };  new_tweets.k.data.in_reply_to_screen_name = 'other_user'; new_tweets.k.data.text = 'tweet text';  // Will create the JSON string you're looking for. var json = JSON.stringify(new_tweets); 

You can also do it all at once:

var new_tweets = {   k: {     tweet_id: 98745521,     user_id: 54875,     data: {       in_reply_to_screen_name: 'other_user',       text: 'tweet_text'     }   } } 
like image 156
Dave Ward Avatar answered Sep 28 '22 07:09

Dave Ward