【问题标题】:adding new dict to json output python将新字典添加到 json 输出 python
【发布时间】:2014-02-24 09:36:02
【问题描述】:

对 json 非常陌生,所以如果我在这里使用了错误的术语,请原谅。我尝试使用更新的 twitter 信息每 x 分钟创建一个 json 文件的任何方式。现在我知道我可以只使用 twitter api 并获取我需要的东西,但我想搞砸一点。我的问题是获得一个新的密钥/字典?或者对于在 for 语句中添加的每个新项目,它被称为什么。

我想得到什么

[
  {
    "name": "thename",
    "date": "thedate",
    "text": "thetext"
  }, <--- trying to get that little comma
  {
    "name": "thename",
    "date": "thedate",
    "text": "thetext"
  }
]

现在我得到了我想要的数据,但不是逗号。它输出了所有内容,但与使它有效的那个小小的字符不应该是一样的。

[
  {
    "name": "thename",
    "date": "thedate",
    "text": "thetext"
  } <--- I get this instead for each new object
  {
    "name": "thename",
    "date": "thedate",
    "text": "thetext"
  }
]

这里只是代码的一个 sn-p,其余的应该是解释性的,因为它只是 Twitter oauth 的东西。

for player in users:
    statuses = api.GetUserTimeline(screen_name=player, count=10)
    print "["

    for s in statuses:
            print json.dumps('timestamp': s.created_at,'username': s.user.name,'status': s.text)
    print "]"

还有一种更好的方法可以在开始和结束时使用 [],因为我知道这很丑陋而且不合适,我敢打赌 XD。就像我说的 json/python 方面的新手,但它是一个很好的学习体验。

【问题讨论】:

  • 您实际上并没有在 for 循环中打印逗号。但是,@poke 的答案是可行的。让 json 处理整个 json 消息。

标签: python json twitter


【解决方案1】:

与其尝试自己构建 JSON 数组,不如让 JSON 编码器也为您完成。为此,您只需将对象列表传递给json.dumps。因此,与其单独打印每个 JSON 对象,不如将它们收集到一个列表中,然后转储:

allstatuses = []
for player in users:
    statuses = api.GetUserTimeline(screen_name=player, count=10)
    for s in statuses:
        allstatuses.append({'timestamp': s.created_at, 'username': s.user.name, 'status': s.text})

print(json.dumps(allstatuses))

【讨论】:

  • 工作就像一个魅力,我知道必须有更好的方法。只是找不到一个好的教程。谢谢戳。
猜你喜欢
  • 2015-03-21
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 2022-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多