如何将JSON转换为格式化的嵌套数组?

时间:2018-11-07 03:06:27

标签: python json

假设我有由纬度,经度和位置组成的JSON数据。我想使用这些值并将它们作为仅包含纬度和经度的JSON字符串返回。

如何在python中执行此操作? (注意:纬度和经度必须转换为浮点值)

输入示例:

object =
  [{"latitude": "48.8566",
    "longitude": "2.3522",
    "location": "Paris"
   },
   {"latitude": "51.5074",
    "longitude": "-0.1278",
    "location": "London"
   }]

预期输出:

"[[48.8566, 2.3522], [51.5074, -0.1278]]"

2 个答案:

答案 0 :(得分:0)

首先将对象转换为具有经度和纬度的列表:

result = [[_.get('latitude'), _.get('longitude')] for _ in object]

然后使用json模块转储列表:

str_result = json.dumps(result)

记住要导入json模块

答案 1 :(得分:0)

from json import dumps


obj = [
    {"latitude": "48.8566", "longitude": "2.3522", "location": "Paris" }, 
    {"latitude": "51.5074", "longitude": "-0.1278", "location": "London" }
]


def return_type(val):
    try:
        return type(float(val))
    except:
        return type(val)

resp = [
    [
        v
        for k, v in item.items() if return_type(v) is float
    ]
    for item in obj
]
print(dumps(resp))