簡體   English   中英

從python讀取json文件

[英]Read json file from python

我正在嘗試使用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作為變量名。 它將隱藏您導入的模塊引用。 為變量使用不同的名稱。

除此之外,代碼傳遞文件對象,而json.loads接受一個字符串。

傳遞一個文件內容:

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

或使用接受類文件對象的json.load

json_data = json.load(json_file)
import json
f = open( "fileToOpen.json" , "rb" )
jsonObject = json.load(f)
f.close()

看起來你正在以相當復雜的方式做。

像這樣嘗試:-

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

考慮到 json 文件的路徑設置為變量json_file

import json

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

print json_data

我做這個....

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM