0

我有一个很大的 json 文件,格式如下:

{
            "enTitle": “my product",
            "esTitle": “es prod",
            "esDescription": “es description",
            "enDescription": “description",
            "URL": “url",
            "Image": “imagepath",
            "HasLandingPage": "1",
            "AddInfo": "info"
        }

我怎么可能将其更改为以下格式:这可能吗?我需要它采用这种格式,这样我就可以将它作为文档添加到搜索引擎 api(elastic swiftype) 中。我看了很多问题找不到我需要的东西。如果重复,请提前道歉。有没有办法为此转换编写程序?

    {"name": "enTitle", "value": "my product", "type": "string"},
    {"name": "esTitle", "value": "es prod", "type": "string"},
    {"name": "esDescription", "value": "es description", "type": "string"},
    {"name": "enDescription", "value": "description", "type": "string"},
    {"name": "URL", "value": "url", "type": "string"},
    {"name": "Image", "value": "imagepath", "type": "string"},
    {"name": "HasLandingPage", "value": "1", "type": "string"},
    {"name": "AddInfo", "value": "info", "type": "string"}
4

1 回答 1

1

一个字典需要唯一的键,你可以将多个字典放在一个列表中。

import json
dict_type = {"enTitle": "my product",
            "esTitle": "es prod",
            "esDescription": "es description",
            "enDescription": "description",
            "URL": "url",
            "Image": "imagepath",
            "HasLandingPage": "1",
            "AddInfo": "info"
        }


def check_type(var):
    if isinstance(var, str):
        return 'string'
    elif isinstance(var, int):
        return 'interger'
    elif isinstance(var, float):
        return 'float'
    elif isinstance(var, bool):
        return 'boolean'

swift_type = list()
for key,val in dict_type.items():
    swift_type.append({"name": key, "value": val, "type": check_type(val)})

print(*swift_type, sep='\n')

# Coverted to json
swift_type = json.dumps(swift_type)
于 2019-01-22T19:53:58.930 回答