首页 > 解决方案 > 从请求中获取的python字典(json)读取时,Pyspark数据帧损坏记录,编码问题

问题描述

我正在使用 Requests 库进行 REST api 调用。

response = requests.get("https://urltomaketheapicall", headers={'authorization': 'bearer {0}'.format("7777777777777777777777777777")}, timeout=5)

当我做response.json()

我得到了这些值的密钥

{'devices': '....iPhone\xa05S, iPhone\xa06, iPhone\xa06\xa0Plus, iPhone\xa06S'}

当我这样做时,print(response.encoding)我得到None

当我这样做时,print(type(data[devices]))我得到<class 'str'>

如果我这样做了,print(data[devices])我会得到'....iPhone 5S, iPhone 6, iPhone 6 Plus, iPhone 6S'没有特殊字符的。

现在如果做

new_dict={}
new_val = data[devices]
new_dict["devices"] = new_val
print(new_dict["devices"])

我也会得到新字典中的特殊字符。

有任何想法吗?

我想摆脱特殊字符,因为我需要读取这些 json 并将其放入 pyspark 数据帧中,使用这些字符我得到一个_corrupted_record

rd= spark.sparkContext.parallelize([data])
df = spark.read.json(rd)

我想避免像.replace("\\xa0"," ")

标签: pythonapache-sparkencodingpysparkpython-requests

解决方案


A0是一个不间断的空间。它只是字符串的一部分。它只是这样打印,因为您正在倾倒整个 dict 的 repr。如果您打印单个字符串,它将简单地打印为正确的不间断空格:

>>> print({'a': '\xa0'})
{'a': '\xa0'}
>>> print('\xa0')
 
>>>

推荐阅读