修改对象中的JSON键/值对

时间:2018-07-28 00:21:25

标签: python json formatting

我有一个JSON文件,该文件来自进行的API调用。

问题在于“ 名称”值实际上与其他值“ smb_nt_ms18_jan_4056890

相关

名为“ attribute_value”和“ attribute_name”的键对我来说毫无价值。

我想将“ name”作为键,将“ smb_nt_ms18_jan_4056890”作为值。 有没有办法在Python中做到这一点?

JSON如下:

{
"attributes": [
    {
        "attribute_value": "smb_nt_ms18_jan_4056890",
        "attribute_name": "name"
    },
    {
        "attribute_value": "MS18-4057142",
        "attribute_name": "msft"
    }
],
}

感谢您的建议和帮助。

1 个答案:

答案 0 :(得分:1)

不要认为这是JSON。解析后,它只是一本字典,其唯一的值是字典列表。您想转换那些字典。


首先,如何转换此词典:

d = {'attribute_value': 'smb_nt_ms18_jan_4056890', 'attribute_name': 'name'}

…进入这一个:

{'name': 'smb_nt_ms18_jan_4056890'}

那很简单:

d = {d['attribute_name']: d['attribute_value']}

我们将其包装在一个函数中:

def transform_attribute(d):
    return {d['attribute_name']: d['attribute_value']}

好的,现在,如果您有此类字典的列表,例如:

ds = [
    {'attribute_value': 'smb_nt_ms18_jan_4056890', 'attribute_name': 'name'},
    {'attribute_value': 'MS18-4057142', 'attribute_name': 'msft'}
]

...您如何转换所有这些?只需编写列表理解即可:

ds = [transform_attribute(d) for d in ds]

再次,让我们做一个函数:

def transform_attributes(ds):
    return [transform_attribute(d) for d in ds]

好的,因此,如果您有一个dict的值是这样的列表,那么如何转换它:

dds = {
    "attributes": [
        {'attribute_value': 'smb_nt_ms18_jan_4056890', 'attribute_name': 'name'},
        {'attribute_value': 'MS18-4057142', 'attribute_name': 'msft'}
    ]}

那只是字典理解:

dds = {key: transform_attributes(ds) for key, ds in dds.items()}

您也可以将其包装起来:

def transform_attributes_dict(dds):
    return {key: transform_attributes(value) for key, value in dds.items()}

或者可能不是字典理解;也许您只想更改与'attributes'关联的值?您的示例只有一个键/值,因此很难知道您想要哪个。但这甚至更容易:

dds['attributes'] = transform_attributes(dds['attributes'])

如果您想使其变得更简洁,可以将函数内联到一个大表达式的中间。但是,如果您一直坚持下去,可能不太容易阅读:

dds = {key: transform_attributes(value) for key, value in dds.items()}

dds = {key: [transform_attribute(d) for d in value] for key, value in dds.items()}

dds = {key: [{d['attribute_name']: d['attribute_value']} for d in value]
       for key, value in dds.items()}
相关问题