2013-04-22 24 views
0

我想創建和顯示字符串值的數組。 首先我嘗試從字符串創建一個JSON值, 然後我嘗試顯示它的鍵/值。在Python中創建JSON從字符串不工作

我得到的錯誤:在最後一個規則無效語法... 忙整整一個晚上,卻找不到DIT出來:(

Python3代碼:

import urllib.request 
import urllib.parse 
import json 

user = 'user' 
pw = 'password' 

login_url = 'http://www.xxxxxxx.nl/test/index.php' 

data = urllib.parse.urlencode({'user': user, 'pw': pw}) 
data = data.encode('utf-8') 
# adding charset parameter to the Content-Type header. 
request = urllib.request.Request(login_url) 
request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8") 

f = urllib.request.urlopen(request, data) 

## returning content from webpage: {"A":"aap","B":"noot","C":"mies"} 

#json.JSONDecoder().decode(f) 
#json.JSONDecoder.raw_decode(f) 
#test = print(f.read().decode('utf-8')) 
test = f.read().decode('utf-8') 
#print (test) 
#test2 = json.JSONDecoder().decode(test) 

test = '{"A":"aap","B":"noot","C":"mies"}' 
dest = json.loads(test) 
print dest['A'] ## <<< invalid syntax ?? 

#json.loads(test2) 
+1

備註:您不是從字符串中創建「JSON對象」。沒有像JSON對象那樣的東西。這是JSON的_string_。你正在從一個字典/對象的JSON字符串表示中創建一個'dict'(甚至不是某種特殊的'dict')。 – abarnert 2013-04-22 22:11:07

回答

3

在Python 3.X - print是一個功能(即:不再像以前那樣在Python 2.x的一份聲明中) - 你需要使用:的

print(dest['A']) 

代替:

print dest['A'] 
+0

aaaaaaaaaaaarrrrrrrrrrgggg ...花了幾個小時就可以了!生活可以很容易:)謝謝!!!!! – Terradon 2013-04-22 21:54:36