【问题标题】:creating JSON in python from string not working从字符串在python中创建JSON不起作用
【发布时间】:2013-04-15 22:56:27
【问题描述】:

我正在尝试从字符串值创建和显示数组。 首先我尝试从字符串创建一个 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)

【问题讨论】:

  • 旁注:您不是从字符串创建“JSON 对象”。没有 JSON 对象之类的东西。它是 JSON 的 string。您正在从字典/对象的 JSON 字符串表示中创建 dict(甚至不是某种特殊的 dict)。

标签: python json python-3.x


【解决方案1】:

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

print(dest['A'])

代替:

print dest['A'] 

【讨论】:

  • aaaaaaaaaaaarrrrrrrrrrgggg...花了几个小时!生活本来可以很轻松的:)谢谢!!!!!!
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 2013-01-19
  • 2018-07-27
相关资源
最近更新 更多