Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

javascript - 将Javascript对象编码为Json字符串(Encoding Javascript Object to Json string)

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 encodejson function.(基本上我想有一些像php encodejson函数。)   ask by Lukas Oppermann translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unless the variable k is defined, that's probably what's causing your trouble.(除非定义变量k ,否则这可能是导致您麻烦的原因。)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...