Encoding Javascript Object to Json string

后端 未结 2 2025
感情败类
感情败类 2020-11-29 02:23

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]         


        
相关标签:
2条回答
  • 2020-11-29 02:50

    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'
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-29 02:53

    You can use JSON.stringify like:

    JSON.stringify(new_tweets);
    
    0 讨论(0)
提交回复
热议问题