2014-04-29 48 views
0

我是新來的Python並閱讀了這篇文章,它似乎很容易,但由於某種原因我無法調試錯誤。我猜測這是一件很簡單的......嘗試在Python中加載JSON字符串時出錯

2功能

def get_json(): return json.load(open('environment.json', 'r'))

def curlopia(j_son=get_json()): sf_url = j_son['sf_sandbox_url']['url'] grant_type = j_son['oauth_parms']['grant_type'] client_id = j_son['oauth_parms']['client_id'] client_secret = j_son['oauth_parms']['client_secret'] username = j_son['oauth_parms']['username'] password = j_son['oauth_parms']['password'] param = '-d'

我有它返回一個JSON字符串一個subprocess.call捲曲聲明。

x=subrpocess.call(["curl", sf_url, param, "grant_type=%s" % (grant_type), param, "client_id=%s" % (client_id), param, "client_secret=%s" % (client_secret), param, "username=%s" % (username), param, "password=%s" % (password)])

x=os.system('curl {0} -d "grant_type={1}" -d "client_id={2}" -d "client_secret={3}" -d "username={4}" -d "password={5}" -H "X-PrettyPrint:1"'.format(sf_url, grant_type, client_id, client_secret, username, password))

當我打印x中的結果是具有在端尾隨零。

{"id":"https://[email protected]/","issued_at":"xxxxxxxxxxx","token_type":"Bearer","instance_url":"xxxxxxxxxx","signature":"xxxxxxxxx","access_token":"xxxxxxxxxxxxx"}0

不確定爲什麼。

當我做

json.loads(x)

給我下面的錯誤。此外,我曾嘗試各種組合

文件「/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/ 初始化 py」爲,線326,在負載 回報_default_decoder .decode(s)

文件「/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py」,行360,解碼 obj,end = self .raw_decode(s,idx = _w(s,0).end())

我試圖理解爲什麼會有一個尾隨零,如果錯誤是相關的。如果是的話可以有人建議繞過它,也許C這樣做的直接方法。

謝謝

+0

你顯然試圖加載無效的JSON,最後的零將會打破它。不知道你在'curl語句'中有什麼。 –

回答

1

您正在嘗試加載無效的JSON文檔。

從你引用curl我猜,你需要通過一些http請求來獲得這個文檔。

嘗試通過使用requests庫來獲取它。

import requests 
url = "http://example.com/api" 
req = requests.get(url) 
assert req.ok 
data = req.json() 
print data 

您真實的案例可能需要不同的URL,方法(POST ...),可能頭,但這些你們已經從現有的捲曲陳述知道)

+0

感謝您的回覆。你對無效的JSON是正確的。 當我在終端中使用相同的curl語句時,我得到一個有效的JSON。無效的JSON僅從python腳本返回,我能夠在打印從subprocess.call或os.system返回的結果時看到它。 我也檢查了.json文件的編碼並嘗試了UTF-8和UTF-16。不幸的是,這兩個結果都是一樣我已經更新了最初的問題以反映捲曲聲明。 請看看,讓我知道。 – user1126946

+0

隨着更新問題,如果你認爲我必須發佈一個新問題,我會這樣做。乾杯 – user1126946

+0

雖然這不是我所做的解決這個問題,我同意的迴應。 – user1126946