Change JSON structure to be suitable for elastic swiftype

74 Views Asked by At

I have a big json file, with the format below:

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

How can I possibly change it to the format below: is that possible? I need it to be in this format so I can add it to a search engine api(elastic swiftype) as document. I looked a lot of questions couldn't find what I need. Apologize in advance if it's duplicate. is there a way to write a program for this conversion?

    {"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"}
1

There are 1 best solutions below

1
On BEST ANSWER

A dict needs unique keys, you can put multiple dicts in a list.

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)