【问题标题】:Format some JSON object with certain fields on one-line?用一行上的某些字段格式化一些 JSON 对象?
【发布时间】:2020-03-03 07:57:00
【问题描述】:

我想重新格式化一个 JSON 文件,以便具有某些特定键的某些对象(字典)在一行上。

例如,任何带有 name 键的对象都应该出现在一行中:

{
  "this": "that",
  "parameters": [
    { "name": "param1", "type": "string" },
    { "name": "param2" },
    { "name": "param3", "default": "@someValue" }
  ]
}

生成 JSON 文件,其中包含编程语言数据。单行的某些字段使目视检查/审查变得更加容易。

在写入之前,我尝试覆盖 python json.JSONEncoder 以将匹配的 dict 转换为 string,只是为了实现字符串中的引号 " 在结果 JSON 文件中再次转义,这违背了我的目的。

我还查看了jq,但无法找到解决方法。我根据行长找到了类似的问题和解决方案,但是我的要求更简单,我不希望更改其他较短的行。仅限某些对象或字段。

【问题讨论】:

标签: python json jq pretty-print


【解决方案1】:

此代码用唯一字符串 (UUID) 递归替换数据中所有适当的 dicts 并记录这些替换,然后在缩进的 JSON 字符串中,将唯一字符串替换为所需的原始单行 JSON。

replace 返回一对:

  • 输入参数数据的修改版本
  • JSON 字符串对的列表,其中每对的第一个值应替换为最终漂亮打印 JSON 中的第二个值。
import json
import uuid


def replace(o):
    if isinstance(o, dict):
        if "name" in o:
            replacement = uuid.uuid4().hex
            return replacement, [(f'"{replacement}"', json.dumps(o))]
        replacements = []
        result = {}
        for key, value in o.items():
            new_value, value_replacements = replace(value)
            result[key] = new_value
            replacements.extend(value_replacements)
        return result, replacements
    elif isinstance(o, list):
        replacements = []
        result = []
        for value in o:
            new_value, value_replacements = replace(value)
            result.append(new_value)
            replacements.extend(value_replacements)
        return result, replacements
    else:
        return o, []


def pretty(data):
    data, replacements = replace(data)
    result = json.dumps(data, indent=4)
    for old, new in replacements:
        result = result.replace(old, new)
    return result


print(pretty({
    "this": "that",
    "parameters": [
        {"name": "param1", "type": "string"},
        {"name": "param2"},
        {"name": "param3", "default": "@someValue"}
    ]
}))

【讨论】:

  • 不错!效果很好!您介意添加一些基本解释吗?这将有助于其他可能希望将其扩展到其他用例的人。例如,我还想单行某些字段值(除了某些字典)。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多