【问题标题】:Read json file from python从python读取json文件
【发布时间】:2014-11-28 11:14:44
【问题描述】:

我正在尝试使用 json 模块从 python 脚本中读取 json 文件。经过一番谷歌搜索,我发现了以下代码:

with open(json_folder+json) as json_file:
        json_data = json.loads(json_file)
        print(json_data)

json_folder+json 是 json 文件的路径和名称。我收到以下错误:

str object has no attribute loads. 

【问题讨论】:

  • 如果json是带文件名的字符串,你想通过在字符串上调用loads来达到什么目的?

标签: python json file


【解决方案1】:

代码使用json 作为变量名。它将隐藏您导入的模块引用。为变量使用不同的名称。

除此之外,代码是传递文件对象,而json.loads 接受一个字符串。

传递一个文件内容:

json_data = json.loads(json_file.read())

或使用json.load 接受类似文件的对象。

json_data = json.load(json_file)

【讨论】:

    【解决方案2】:
    import json
    f = open( "fileToOpen.json" , "rb" )
    jsonObject = json.load(f)
    f.close()
    

    看来你的做法相当复杂。

    【讨论】:

      【解决方案3】:

      试试这样:-

      json_data=open(json_file)
      data = json.load(json_data)
      json_data.close()
      

      【讨论】:

        【解决方案4】:

        考虑到你的json文件的路径设置为变量json_file

        import json
        
        with open(json_file, "rb") as f:
            json_data = json.load(f)
        
        print json_data
        

        【讨论】:

          【解决方案5】:

          我做这个....

          import urllib2
          
          link_json = "\\link-were\\"
          link_open = urllib2.urlopen(link_json) ## Open and Return page.
          link_read = link_open.read()           ## Read contains of page.
          
          json = eval(link_read)[0]              ## Transform the string of read in link_read and return the primary dictionary ex: [{dict} <- return this] <- remove this
          
          print(json['helloKey'])
          
          Hello World
          

          【讨论】:

          • 不确定这有什么关系。
          猜你喜欢
          • 1970-01-01
          • 2017-04-21
          • 2021-06-01
          • 2021-10-21
          • 1970-01-01
          • 2013-12-10
          相关资源
          最近更新 更多