将 Javascript 对象编码为 Json 字符串 [英] Encoding Javascript Object to Json string
问题描述
我想将 Javascript 对象编码为 JSON 字符串,但遇到了相当大的困难.
I want to encode a Javascript object into a JSON string and I am having considerable difficulties.
对象看起来像这样
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";
我想把它放到一个 JSON 字符串中,把它放到一个 ajax 请求中.
I want to get this into a JSON string to put it into an ajax request.
{'k':{'tweet_id':98745521,'user_id':54875, 'data':{...}}}
你得到了图片.无论我做什么,它都不起作用.所有 JSON 编码器,如 json2 之类的产品
you get the picture. No matter what I do, it just doesn't work. All the JSON encoders like json2 and such produce
[]
好吧,这对我没有帮助.基本上我想有类似 php encodejson
函数的东西.
Well, that does not help me. Basically I would like to have something like the php encodejson
function.
推荐答案
除非定义了变量 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'
}
}
}
这篇关于将 Javascript 对象编码为 Json 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!