将 Javascript 对象编码为 Json 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6810084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:17:58  来源:igfitidea点击:

Encoding Javascript Object to Json string

javascriptobjectjsonjavascript-objects

提问by Lukas Oppermann

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

我想将 Javascript 对象编码为 JSON 字符串,但遇到了相当大的困难。

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.

我想把它放到一个 JSON 字符串中,把它放到一个 ajax 请求中。

{'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

你明白了。无论我做什么,它都不起作用。所有 JSON 编码器,如 json2 和此类产品

[]

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

嗯,这对我没有帮助。基本上我想要像phpencodejson函数这样的东西。

回答by Dave Ward

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

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

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'
    }
  }
}

回答by Luca C.

You can use JSON.stringifylike:

你可以使用JSON.stringify像:

JSON.stringify(new_tweets);