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

I want to get this into a JSON string to put it into an ajax request.

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

[]

这对我没有帮助.基本上,我希望有一些像PHPencodejson的函数.

推荐答案

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

Json相关问答推荐

JQ -迭代对象,不带数组

无法根据vega规范中的条件设置文本 colored颜色

将嵌套的json中的字符串强制转换为数字

替换字符串中特殊字符的Jolt变换

如何使用JQ打印每个根级对象键一行?

Flutter -控制器问题-JSON API

用于参考的Jolt变换

使用 Redis 作为键值存储

如何获取 JSON 对象字段值和同一 JSON 对象的下一个数组中的字段值?

将来自 Golang 的 JSON API 调用响应输出到 nextjs 前端

JOLT - 如果对象内部存在键,则将对象移动到数组

如何从 json 中获取单个元素?

从 PowerShell 编辑 Windows 终端配置文件设置 JSON

如何在linux中用jq过滤json数组?

如何配置spring mvc 3在json响应中不返回null对象?

从 JSON 对象中删除键值对

未捕获的类型错误:无法读取 null 的属性props

json.dumps 打乱了顺序

如何获取json格式的KendoGrid显示数据?

使用 gson 反序列化对象的特定 JSON 字段