Py学习  »  Python

如何在python中简化json文件操作

TC2 • 4 年前 • 389 次点击  

    Rem_Conf['RemediationConfigurations'][0]['Parameters']['AutomationAssumeRole']['StaticValue']['Values'][0] = rolearn
    Rem_Conf['RemediationConfigurations'][0]['Parameters']['GranteeId']['StaticValue']['Values'][0] = canid
    Rem_Conf['RemediationConfigurations'][0]['Parameters']['TargetBucket']['StaticValue']['Values'][0] = targetbucket

如何压缩它以满足79个字符的pydocstyle限制?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53076
 
389 次点击  
文章 [ 4 ]  |  最新文章 4 年前
Michael Doubez
Reply   •   1 楼
Michael Doubez    4 年前

我只需要使用一个中间值:

Parameters = Rem_Conf['RemediationConfigurations'][0]['Parameters']
Parameters['AutomationAssumeRole']['StaticValue']['Values'][0] = rolearn
Parameters['GranteeId']['StaticValue']['Values'][0] = canid
Parameters['TargetBucket']['StaticValue']['Values'][0] = targetbucket
MasterAler
Reply   •   2 楼
MasterAler    4 年前

其他的答案甚至更好,只是想补充一下,至少你可以用这样的反斜杠:

Rem_Conf['RemediationConfigurations'][0]['Parameters'] \
            ['AutomationAssumeRole']['StaticValue']['Values'][0] = rolearn
Rem_Conf['RemediationConfigurations'][0]['Parameters'] \
            ['GranteeId']['StaticValue']['Values'][0] = canid
Rem_Conf['RemediationConfigurations'][0]['Parameters'] \
            ['TargetBucket']['StaticValue']['Values'][0] = targetbucket

Python文档说明如下:

2.1.5条。显式换行

反斜杠字符( \ ),如下所示:当物理行结束于 反斜杠不是字符串文字或注释的一部分,它是 反斜杠和以下行尾字符。

Jakub
Reply   •   3 楼
Jakub    4 年前

你可以用圆括号括起来,如下所示。当然,你也可以随意使用格式。这就是 black 格式化程序输出。

(
    Rem_Conf["RemediationConfigurations"][0]["Parameters"]["AutomationAssumeRole"][
        "StaticValue"
    ]["Values"][0]
) = rolearn
(
    Rem_Conf["RemediationConfigurations"][0]["Parameters"]["GranteeId"]["StaticValue"][
        "Values"
    ][0]
) = canid
(
    Rem_Conf["RemediationConfigurations"][0]["Parameters"]["TargetBucket"][
        "StaticValue"
    ]["Values"][0]
) = targetbucket

嗯,这是一种可读的格式:

(Rem_Conf
    ["RemediationConfigurations"]
    [0]
    ["Parameters"]
    ["AutomationAssumeRole"]
    ["StaticValue"]
    ["Values"]
    [0]
) = rolearn

黑色

Rem_Conf["RemediationConfigurations"][0]["Parameters"]["AutomationAssumeRole"][
    "StaticValue"
]["Values"][0] = rolearn
Rem_Conf["RemediationConfigurations"][0]["Parameters"]["GranteeId"]["StaticValue"][
    "Values"
][0] = canid
Rem_Conf["RemediationConfigurations"][0]["Parameters"]["TargetBucket"]["StaticValue"][
    "Values"
][0] = targetbucket
JBirdVegas
Reply   •   4 楼
JBirdVegas    4 年前

一种方法是用短命名变量替换内联键

cfg='RemediationConfigurations'
params='Parameters'
role='AutomationAssumeRole'
sval='StaticValue'
val='Values'
guid='GranteeId'
tbuk='TargetBucket'
Rem_Conf[cfg][0][params][role][sval][val][0] = rolearn
Rem_Conf[cfg][0][params][guid][sval][val][0] = canid
Rem_Conf[cfg][0][params][tbuk][sval][val][0] = targetbucket

60 它使读者很清楚价值观的模式