我有一个包含json数据的列表,如下所示:
txt
[“ {'type':'Point','coordinates':[35.51635659,139.5662442]}”,“ “ {'type':'Point','coordinates':[51.50178423,-0.05362636]}”]
我正在尝试从坐标中提取经度和纬度,但是我对此很挣扎。
当我尝试:
for each in txt:
print(each)
它返回:
{'type':'Point','coordinates':[35.51635659,139.5662442]} {'type':'Point','coordinates':[51.50178423,-0.05362636]}
当我尝试:
json_normalize(json.loads(txt))
我收到以下错误:
TypeError跟踪(最近的呼叫 最后) ----> 1 json_normalize(json.loads(txt))
C:\ ProgramData \ Anaconda3 \ lib \ json__init __。py加载(s,编码, cls,object_hook,parse_float,parse_int,parse_constant, object_pairs_hook,** kw) 其他339 340如果不是isinstance(s,(bytes,bytearray)): -> 341提高TypeError(f'JSON对象必须为str,bytes或bytearray,' 342 f'not {s。 class 。 name }') 343 s = s.decode(detect_encoding(s),'surrogatepass')
TypeError:JSON对象必须是str,字节或字节数组,而不是列表
如果有人可以帮助,将不胜感激
谢谢
答案 0 :(得分:1)
字典是一个字符串,因此您需要使用ast.literal_eval()
或用双引号替换然后使用json.loads()
。两种方法都可以得到co药:
给出:
txt = ["{'type': 'Point', 'coordinates': [35.51635659, 139.5662442]}", "{'type': 'Point', 'coordinates': [51.50178423, -0.05362636]}"]
选项1:
import json
for each in txt:
each = each.replace("'", '"')
jsonObj = json.loads(each)
print (jsonObj['coordinates'])
选项2:
import ast
for each in txt:
each = ast.literal_eval(each)
print(each['coordinates'])
输出:
[35.51635659, 139.5662442]
[51.50178423, -0.05362636]