103

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.

1
  • 5
    what did you actually try? please provide some code of your trials...
    – user57508
    Jul 24, 2011 at 22:15

2 Answers 2

163

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'
    }
  }
}
5
  • 3
    You are a genius. Thank you very much. The k was defined. The problem was me being stupid using new Array() instead of an object {}. Jul 24, 2011 at 22:21
  • Works perfect... I make a test and result are awesome. Thanks. console.info(json); console.log(new_tweets["k"]); console.log(new_tweets["k"]["user_id"]); console.log(new_tweets["k"]["data"]["text"]);
    – equiman
    Aug 13, 2013 at 0:50
  • After all this time reading about CORS and Chrome security, this is a simple and effective way to encode JSON data. A very well-deserved +1
    – ashes999
    Feb 4, 2014 at 2:37
  • 1
    @TomášZato: Why specifically would it be? JSON.stringify predates PHP's json_encode, if that's what you're alluding to.
    – Dave Ward
    Oct 20, 2014 at 0:37
  • Yes, that was what I was thinking. I found out about JSON very recently. In past, I used eval to parse JSON responses. I was happy the eval will be gon from my code. Oct 20, 2014 at 0:45
16

You can use JSON.stringify like:

JSON.stringify(new_tweets);
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.