在python中向json添加一个属性

时间:2018-03-23 04:37:28

标签: python json

我有以下json,我想再添加一个属性:

[   {
        "A": 1,
        "B": "str"
    },
    {
        "A": 2,
        "B": "str2"
    },
    {
        "A": 3,
        "B": "str3"
    }
]

所以我想要这样的事情:

[   {
        "A": 1,
        "B": "str",
        "C": "X"
    },
    {
        "A": 2,
        "B": "str2",
        "C": "X"
    },
    {
        "A": 3,
        "B": "str3",
        "C": "X"
    }
]

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:3)

遍历列表中的每个dict obj并添加list1 = [ { "A": 1, "B": "str" }, { "A": 2, "B": "str2" }, { "A": 3, "B": "str3" } ]

列出之前

for l in list1:
    l['C'] = 'X'

print(list1)

代码

[{'A': 1, 'B': 'str', 'C': 'X'}, {'A': 2, 'B': 'str2', 'C': 'X'}, {'A': 3, 'B': 'str3', 'C': 'X'}]

列表输出

df.first.get(0).toString
//res0: String = 1
df.first.get(0).toString.toLong
//res1: Long = 1
df.first.get(0).toString.toFloat
//res2: Float = 1.0

答案 1 :(得分:2)

>>> j = [ { "A": 1, "B": "str" }, { "A": 2, "B": "str2" }, { "A": 3, "B": "str3" } ]
>>> [i.update({'C': 'X'}) for i in j]
>>> j
[{'A': 1, 'B': 'str', 'C': 'X'}, {'A': 2, 'B': 'str2', 'C': 'X'}, {'A': 3, 'B': 'str3', 'C': 'X'}]

或者,根据coldspeed的评论:

>>> for item in j:
...     item['C'] = 'X'  
... 
>>> j
[{'A': 1, 'B': 'str', 'C': 'X'}, {'A': 2, 'B': 'str2', 'C': 'X'}, {'A': 3, 'B': 'str3', 'C': 'X'}]