102

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... Commented Jul 24, 2011 at 22:15

2 Answers 2

162

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

5 Comments

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 {}.
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"]);
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
@TomášZato: Why specifically would it be? JSON.stringify predates PHP's json_encode, if that's what you're alluding to.
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.
16

You can use JSON.stringify like:

JSON.stringify(new_tweets);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.