在python中创建JSON从字符串不起作用

时间:2013-04-22 21:45:11

标签: python json python-3.x

我正在尝试从字符串值创建和显示数组。 首先我尝试从字符串创建一个JSON值, 然后我尝试从中显示键/值。

我收到错误:上一条规则的语法无效... 整个晚上都很忙,但找不到了:(

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 个答案:

答案 0 :(得分:3)

在Python 3.x中 - print是一个函数(即:不再是Python 2.x中的语句) - 您需要使用:

print(dest['A'])

而不是:

print dest['A']