当前位置: 首页 > 知识库问答 >
问题:

从对象的 JSON 数组访问键值 Python

鲁才艺
2023-03-14

过去几天我一直在研究如何做到这一点,但毫无结果。

我有一个JSON文件,其中包含大量JSON对象,如下所示:

[{
    "tweet": "@SHendersonFreep @realDonaldTrump watch your portfolios go to the Caribbean banks and on to Switzerland. Speculation without regulation",
    "user": "DGregsonRN"
},{
    "tweet": "RT @CodeAud: James Mattis Vs Iran.\n\"The appointment of Mattis by @realDonaldTrump got the Iranian military leaders' more attention\". https:\u2026",
    "user": "American1765"
},{
    "tweet": "@realDonaldTrump the oyou seem to be only fraud I see is you, and seem scared since you want to block the recount???hmm cheater",
    "user": "tgg216"
},{
    "tweet": "RT @realDonaldTrump: @Lord_Sugar Dopey Sugar--because it was open all season long--you can't play golf in the snow, you stupid ass.",
    "user": "grepsalot"
},{
    "tweet": "RT @Prayer4Chandler: @realDonaldTrump Hello Mr. President, would you be willing to meet Chairman #ManHeeLee of #HWPL to discuss the #PeaceT\u2026",
    "user": "harrymalpoy1"
},{
    "tweet": "RT @realDonaldTrump: Thank you Ohio! Together, we made history \u2013 and now, the real work begins. America will start winning again! #AmericaF\u2026",
    "user": "trumpemall"
}]

我正在尝试访问每个键和值,并将它们写入csv文件。我相信使用<code>json.loads(json.dumps(文件))</code>应该可以正常的json格式工作,但是因为有一个对象数组,我似乎无法访问每个对象。

converter.py:


    import json
    import csv

    f = open("tweets_load.json",'r')
    y = json.loads(json.dumps(f.read(), separators=(',',':')))
    t = csv.writer(open("test.csv", "wb+"))

    # Write CSV Header, If you dont need that, remove this line
    t.writerow(["tweet", "user"])

    for x in y:
       t.writerow([x[0],x[0]])

grab_tweets.py:


    import tweepy
    import json

    def get_api(cfg):
      auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
      auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
      return tweepy.API(auth)

    def main():

      cfg = {
        "consumer_key"        : "xxx",
        "consumer_secret"     : "xxx",
        "access_token"        : "xxx",
        "access_token_secret" : "xxx"
        }
      api = get_api(cfg)
      json_ret = tweepy.Cursor(api.search, q="@realDonaldTrump",count="100").items(100)
      restapi =""
      for tweet in json_ret:
          rest = json.dumps({'tweet' : tweet.text,'user' :str(tweet.user.screen_name)},sort_keys=True,indent=4,separators=(',',': '))
          restapi = restapi+str(rest)+","
      f = open("tweets.json",'a')
      f.write(str(restapi))
      f.close()

    if __name__ == "__main__":
      main()

到目前为止,输出如下所示:

tweet,user^M
{,{^M
"
","
"^M
 , ^M
 , ^M
 , ^M
 , ^M
"""",""""^M
t,t^M
w,w^M
e,e^M
e,e^M
t,t^M
"""",""""^M
:,:^M
 , ^M
"""",""""^M
R,R^M
T,T^M
 , ^M
@,@^M
r,r^M
e,e^M
a,a^M
l,l^M
D,D^M
o,o^M
n,n^M
a,a^M
l,l^M

我到底做错了什么?

共有1个答案

周鸿光
2023-03-14

原来是json。dumps(),应该深入了解它的作用!谢谢

 类似资料:
  • 问题内容: 我有一系列对象,并且正在使用对其进行迭代,这很容易。该数组如下所示: 我的属性如下所示: 在每个迭代中,等于预期的对象之一。无论如何都可以访问键和对象的值?这样我就可以做这样的事情: 其中== 和== 。我已经尝试做这件事,但总是最终只是step对象的索引(这很有意义)。我只是想弄清楚是否还有另一种语法编写方式,以便我可以获取键和值。 感谢您的任何想法/建议。非常感激。 PS。我目前的

  • 可以使用点号(.),或中括号([])来访问 JSON 对象的值。 使用点号访问对象时,直接使用对象的 key 来访问, key 无须放在双引号中。如: <script>   var myObj, x;   myObj = { "github": "https://github.com/leiqikui" };   x = myObj.github;   document.write(x); </

  • 问题内容: 我有以下JSON对象: 这是来自一个请求,我有成功。 问题是,即使dataJS在控制台中正确显示,我也无法访问JSON对象中的项目。有想法吗? 问题答案: 那是因为您的基础对象也是数组。 我怀疑那会有用

  • 我想访问来自该对象数组的ends\u数据。。。但我不能让它工作。输出未定义。请帮帮我。

  • 我有两个数组:和。 数组中的示例值:。 数组中的值示例:。 我需要创建一个JavaScript对象,将数组中的所有项放在同一个对象中。例如

  • 可能的重复: 我有一个嵌套的数据结构/JSON,我如何访问一个特定的值? 我有一个在JSON数组中返回嵌套对象的服务。我如何在对象中循环并打印所需的数据? 这是我的结果: 这是我要为每个项目(项目1,项目2,项目3,...)打印的内容: 到目前为止我试过: 这只返回“item1”、“item2”等,但我不知道如何访问sourceUuid等