【问题标题】:How to convert list of list (of lists) to json array in python?如何在python中将列表(列表)列表转换为json数组?
【发布时间】:2012-04-03 22:00:44
【问题描述】:

我无法找到如何转换这样的元素的 python 列表:

[[["thisid", 24024502], ["points", [[["lat", 37.8732041], ["lon", -122.2562601]], [["lat", 37.8729153], ["lon", -122.2561566]]]], ["name", "Latimer Hall"]]

到这样的元素的json数组:

{"thisid": 24024502, "points": [{"lat": 37.8732041, "lon": -122.2562601}, {"lat": 37.8729153, "lon": -122.2561566}], "name": "Latimer Hall"}

基本上,我正在尝试将具有内部结构的列表列表转换为 json 中的相应列表。

Plain json.dumps(mylist) 只返回原始列表(我猜,这是因为它也是一个有效的 json 对象......)

非常感谢您提出的任何建议!

【问题讨论】:

  • 为什么不使用字典来存储原始数据?这样会更容易使用,并且还可以序列化为您要查找的 JSON。

标签: python json list


【解决方案1】:

原始代码中的括号不平衡。如果我在开头删除一个括号:

>>> a = [["thisid", 24024502], ["points", [[["lat", 37.8732041], ["lon", -122.2562601]], [["lat", 37.8729153], ["lon", -122.2561566]]]], ["name", "Latimer Hall"]]
>>> b = dict(a)
>>> for i, l in enumerate(b['points']):
...     b['points'][i] = dict(l)
... 
>>> b
{'points': [{'lat': 37.8732041, 'lon': -122.2562601}, {'lat': 37.8729153, 'lon': -122.2561566}], 'thisid': 24024502, 'name': 'Latimer Hall'}
>>> 

那我就可以序列化成json了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-13
    • 2019-01-23
    • 2019-03-12
    • 1970-01-01
    • 2010-12-25
    • 2018-01-06
    • 1970-01-01
    • 2014-03-03
    相关资源
    最近更新 更多