用Python将Collections Counter结果返回为JSON
我对Python不是特别熟悉,但我正在写一个脚本,需要把一个json对象从Python传到PHP。现在我遇到的问题是使用了collections库中的Counter,而这个Counter不能被正确地转成JSON格式(实际上甚至无法编译,这也能理解)。
我遇到了一个错误:ValueError: keys must be a string
这是我的代码片段:
# Make sure items in set are all unique
items = collections.Counter(tuple(item) for item in all_items)
# Print json response
print json.dumps({ 'items': items, 'position': [rAvg, gAvg, bAvg] })
这是我的Counter的样子:
Counter({(11, 11, 15): 8452, (151, 131, 153): 7336, (26, 29, 35): 7324, (83, 81, 100): 5080, (113, 106, 126): 5012, (54, 56, 61): 4627, (193, 193, 194): 3783, (13, 124, 157): 822})
2 个回答
1
JSON 只允许使用字符串作为键,而你的键是元组。要解决这个问题,你需要把它们转换成字符串。
items = collections.Counter(tuple(item) for item in all_items)
items4json = dict(zip(map(str,items.keys()),items.values())
print json.dumps({ 'items': items, 'position': [rAvg, gAvg, bAvg] })
然后再恢复成原来的样子。
import ast
read_dict = json.loads(someFileHandle.read())
items = dict(zip(map(ast.literal_eval,items.keys()),items.values())
2
JSON只允许键是字符串,而你用的是元组。试试:
items = collections.Counter(str(tuple(item)) for item in all_items)
或者也可以试试
items = collections.Counter(str(item) for item in all_items)
(这取决于你想在JSON中如何格式化它们)