且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 Javascript 对象编码为 Json 字符串

更新时间:2023-02-23 11:22:01

除非定义了变量 k,否则这可能是导致您遇到麻烦的原因.像这样的事情会做你想做的:

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);

您也可以一次性完成:

var new_tweets = {
  k: {
    tweet_id: 98745521,
    user_id: 54875,
    data: {
      in_reply_to_screen_name: 'other_user',
      text: 'tweet_text'
    }
  }
}