python - 在json中条带化尾迹空格
问题描述
我有一个包含 1000 多个条目的大 json 文件。这个 json 被送入下游库进行进一步处理。我正在尝试寻找一种更简单的方法来消除值部分中的所有尾随空格。
{
"Country": [
{
"country_name": "Germany ",
"country_capital": " Berlin",
"concept_description": "Germany is also known as Deutschland ",
"country_cities": [
"Frankfurt"
],
"neighbouring_countries": [
" Belgium",
"France "
],
"country_group": "Europe "
},
{
"country_name": " France ",
"country_capital": " Paris",
"concept_description": "Effiel Tower is in paris ",
"country_cities": [
" montpellier"
],
"neighbouring_countries": [
" Belgium",
"Spain "
],
"country_group": "Europe "
}
]
}
我试图使用String.strip()
和列出理解来实现这一点mylist = [[x.strip() for x in y] for y in mylist]
。但是,某些键的值是列表,有些只是字符串。
解决方案
您可以使用递归函数来剥离所有内容吗?
def strip(value):
if isinstance(value, str):
return value.strip()
if isinstance(value, list):
return list(map(strip, value))
# handle dict etc, by recursive call to `strip()`
如果结构是一致的,例如。neighbouring_countries
始终是一个列表,您可以使用任何数据验证库。我更喜欢schema
我自己。
推荐阅读
- java - 使用 maven 通过双击构建可运行的 jar
- php - RewriteRule 指向 index.php
- r - Shiny Flexdashboard 和 shinyAmBarCharts 之间的集成
- java - 是否可以在 main 方法之外使用 Scanner 并仍然调用它?
- r - 如何编写读取文本文件目录、更改它们并保存到同一目录中的 R 函数
- haskell - 每当我尝试在 Cabal 上安装新软件包时,它都会尝试安装以前失败的安装但失败
- python - 如何在 Python 中修改 Protocol-Buffers ScalarMapContainer?
- reactjs - 在同一浏览器中保持用户会话以做出反应
- reactjs - Apollo-graphql 突变中的“mutation_root”是什么?我收到错误消息,提示“mutation_root”中找不到字段
- google-cloud-platform - Terraform GCP service_account vs project vs org