【发布时间】:2018-04-03 21:24:03
【问题描述】:
我正在尝试从通过json.dumps 返回的字典列表中进行过滤。但是,由于它是换行符分隔的 JSON(其中字典不以逗号分隔),因此我收到错误消息。
>>>> print my_data
>>>> {u'mykey': 1234, u'color': u'red'} {u'mykey': 5678, u'color': u'orange'} {u'mykey': 5678, u'color': u'yellow'}
代码:
key = 5678
test_data = json.dumps(my_data)
self.response.write(test_data)
# test_data outputs {"mykey": 1234, "color": "red"} {"mykey": 5678, "color": "orange"} {"mykey": 5678, "color": "yellow"}
test = filter(lambda thedata: thedata['mykey'] == key, test_data)
print test
错误:
test = filter(lambda thedata: thedata['mykey'] == key, test_data)
TypeError: 'NoneType' 对象不可迭代
当我将相同的数据复制到 Python 解释器中时,在每个字典之间添加括号和逗号,它会返回正确的输出。
代码
key = 5678
test_data = [
{"mykey": 1234, "color": "red"},
{"mykey": 5678, "color": "orange"},
{"mykey": 5678, "color": "yellow"}]
test = filter(lambda thedata: thedata['mykey'] == key, test_data)
print test
输出:
[{'color': 'orange', 'mykey': 5678}, {'color': 'yellow', 'mykey': 5678}]
如何修复我的代码或 JSON 输出以便正确过滤?
编辑(更正):
我正在寻找使用self.response.write 而不是print 的解决方案。
在使用@Ashish Ranjan 的答案时,我注意到print 的输出与self.response.write 不同。推荐的解决方案应该使用self.response.write:
test = filter(lambda thedata: thedata['mykey'] == key, test_data)
self.response.write(test)
使用@Ashish 解决方案的当前输出是:
硬编码数据:
my_data = "{u'mykey': 1234, u'color': u'red'} {u'mykey': 5678, u'color': u'orange'} {u'mykey': 5678, u'color': u'yellow'}"
test_data = ast.literal_eval("[" + re.sub(r'({[^\}]*})\s', r'\1,' , my_data) + "]")
test = filter(lambda thedata: thedata['mykey'] == 5678, test_data)
self.response.write(test_data)
[{u'mykey': 1234, u'color': u'red'}, {u'mykey': 5678, u'color': u'orange'}, {u'mykey': 5678, u'color': u'yellow'}][{u'mykey': 1234, u'color': u'red'}, {u'mykey': 5678, u'color': u'orange'}, {u'mykey': 5678, u'color': u'yellow'}]
来自 JSON 对象:
dumped_data = json.dumps(my_data)
test_data = ast.literal_eval("[" + re.sub(r'({[^\}]*})\s', r'\1,' , dumped_data) + "]")
test = filter(lambda thedata: thedata['mykey'] == 5678, test_data)
self.response.write(test_data)
({u'color': u'orange', u'mykey': 5678},)({u'color': u'yellow', u'mykey': 5678},)
注意:即使使用print 进行测试,JSON 数据也无法正确输出结果。相反,它将每条数据打印在单独的行上:
[{u'color': u'orange', u'mykey': 5678}]
[{u'color': u'yellow', u'mykey': 5678}]
所有这些结果都不正确。我不明白为什么self.response.write 不像print 那样工作。 (我以前从未遇到过这个问题,所以任何见解都会有所帮助。)
【问题讨论】:
-
在第一个示例中,
test_data在末尾而不是开头包含]? -
已编辑(test_data 没有括号),谢谢指出
-
你能把你的
my_data发一下吗? -
@bruntime,添加了“修复”算法。但是您能否将
print my_data的输出添加到您的问题中? -
已添加
my_data的输出以进行更多说明
标签: python json python-2.7 google-app-engine