用单行的某些字段格式化某些JSON对象?

问题描述 投票:0回答:1

我想重新格式化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个回答
2
投票

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

replace返回一对:

  • 输入自变量数据的修改版本
  • JSON字符串对列表,其中每对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"}
    ]
}))

© www.soinside.com 2019 - 2024. All rights reserved.