从 json 格式列表中提取值
extract values from json format list
我有一个包含 json 数据的列表,如下所示:
txt
["{'type': 'Point', 'coordinates': [35.51635659, 139.5662442]}",
"{'type': 'Point', 'coordinates': [51.50178423, -0.05362636]}"]
我正在尝试从坐标中提取经度和纬度,但我真的很难解决这个问题。
当我尝试时:
for each in txt:
print(each)
它returns:
{'type': 'Point', 'coordinates': [35.51635659, 139.5662442]}
{'type': 'Point', 'coordinates': [51.50178423, -0.05362636]}
当我尝试时:
json_normalize(json.loads(txt))
我收到以下错误:
TypeError Traceback (most recent call
last) in
----> 1 json_normalize(json.loads(txt))
C:\ProgramData\Anaconda3\lib\json__init__.py in loads(s, encoding,
cls, object_hook, parse_float, parse_int, parse_constant,
object_pairs_hook, **kw)
339 else:
340 if not isinstance(s, (bytes, bytearray)):
--> 341 raise TypeError(f'the JSON object must be str, bytes or bytearray, '
342 f'not {s.class.name}')
343 s = s.decode(detect_encoding(s), 'surrogatepass')
TypeError: the JSON object must be str, bytes or bytearray, not list
如果有人能提供帮助,将不胜感激
谢谢
字典是一个字符串,因此您需要使用 ast.literal_eval()
,或者用双引号替换然后使用 json.loads()
。无论哪种方式都可以获得坐标:
鉴于:
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]
我有一个包含 json 数据的列表,如下所示:
txt
["{'type': 'Point', 'coordinates': [35.51635659, 139.5662442]}", "{'type': 'Point', 'coordinates': [51.50178423, -0.05362636]}"]
我正在尝试从坐标中提取经度和纬度,但我真的很难解决这个问题。
当我尝试时:
for each in txt:
print(each)
它returns:
{'type': 'Point', 'coordinates': [35.51635659, 139.5662442]} {'type': 'Point', 'coordinates': [51.50178423, -0.05362636]}
当我尝试时:
json_normalize(json.loads(txt))
我收到以下错误:
TypeError Traceback (most recent call last) in ----> 1 json_normalize(json.loads(txt))
C:\ProgramData\Anaconda3\lib\json__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 339 else: 340 if not isinstance(s, (bytes, bytearray)): --> 341 raise TypeError(f'the JSON object must be str, bytes or bytearray, ' 342 f'not {s.class.name}') 343 s = s.decode(detect_encoding(s), 'surrogatepass')
TypeError: the JSON object must be str, bytes or bytearray, not list
如果有人能提供帮助,将不胜感激
谢谢
字典是一个字符串,因此您需要使用 ast.literal_eval()
,或者用双引号替换然后使用 json.loads()
。无论哪种方式都可以获得坐标:
鉴于:
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]