' ASCII'编解码器无法解码位置3

时间:2015-06-23 19:24:37

标签: python json

由于值中存在特殊字符,我不确定为什么会出现此错误,我试图使用@Brien提供的递归函数从json获取密钥的值。

http://stackoverflow.com/questions/31010299/json-get-key-path-in-nested-dictionary

import json
with open('data.json') as data_file:    
  j = json.load(data_file)

def find(element, JSON,path,all_paths):
  if element in JSON:
    path = path + element + ' = ' + JSON[element].encode('utf-8')
    print path
    all_paths.append(path)
  for key in JSON:
    if isinstance(JSON[key], dict):      
      find(element, JSON[key],path + key + '.',all_paths)   


all_paths = []
find('userNameField',j,'',all_paths)
print all_paths

2 个答案:

答案 0 :(得分:0)

您的代码存在一些问题:

  1. 当您从JSON调用某个项目时,您应该分配给变量,然后对其进行编码或编码。
  2. 当您对json.load类型的字符串进行编码时,您将其更改为字节。正确编码变量后添加str + byte会引发另一个错误。
  3. 尝试以下方法:

    j = json.load(data_file, encoding='utf-8')
    #....
    path = path + element + ' = ' + str(JSON[element])
    

答案 1 :(得分:-2)

通常当有人试图编码未解码的字符串时会发生此类错误。我建议JSON[element].decode('utf-8')。如果需要,您可以稍后对其进行编码。