【问题标题】:extract values from json format list从 json 格式列表中提取值
【发布时间】:2019-07-29 14:09:26
【问题描述】:

我有一个包含 json 数据的列表,如下所示:

txt

["{'type': '点', '坐标': [35.51635659, 139.5662442]}", "{'type': 'Point', 'coordinates': [51.50178423, -0.05362636]}"]

我正在尝试从坐标中提取经纬度,但我真的在为此苦苦挣扎。

当我尝试时:

for each in txt:
    print(each)

它返回:

{'type': 'Point', 'coordinates': [35.51635659, 139.5662442]} {'类型':'点','坐标':[51.50178423,-0.05362636]}

当我尝试时:

json_normalize(json.loads(txt))

我收到以下错误:


TypeError Traceback(最近调用 最后)在 ----> 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 raise TypeError(f'JSON对象必须是str, bytes or bytearray, ' 342 f'not {s.class.name}') 第343章 = s.decode(detect_encoding(s), 'surrogatepass')

TypeError:JSON 对象必须是 str、bytes 或 bytearray,而不是 list

如果有人能提供帮助,将不胜感激

谢谢

【问题讨论】:

  • 1 for each in txt: ----> 2 print(each['coordinates']) TypeError: string indices must be integers
  • 啊,由于某种原因,字典似乎在字符串中:)。为什么它们是字符串?
  • 数据原本在一个数据框中,我循环遍历它:for each in cords['geo']: txt.append(each)
  • import ast; for each in txt:..x = ast.literal_eval(each);..print(x['coordinates'])
  • 为什么cords['geo'] 在字符串中? :)

标签: python json dataframe geojson


【解决方案1】:

字典是一个字符串,因此您需要使用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]

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 2022-11-19
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    相关资源
    最近更新 更多