Home > Enterprise >  Python JSON/Dict Converting Key:Pair to Key=Pair
Python JSON/Dict Converting Key:Pair to Key=Pair

Time:07-17

I am new to coding in Python and I am trying to convert key:pair's to key=pairs but only in certain parts of a JSON/Dictionary hierarchy.

I currently have this:

 {'AdditionalInfo': 'string',
    'AmiVersion': 'string',
    'Applications': [{
                'AdditionalInfo': {
                    'string': 'string'
                },
                'Args': ['string'],
                'Name': 'string',
                'Version': 'string'
            }]}

And I am trying to get the below:

 {'AdditionalInfo' = 'string',
    'AmiVersion' = 'string',
    'Applications' = [{
                'AdditionalInfo': {
                    'string': 'string'
                },
                'Args': ['string'],
                'Name': 'string',
                'Version': 'string'
            }]}

The original file is in JSON, so the quotes would be double but I have changed these in my logic. So far I have tried json.loads, json.dumps, dict(). All of those continue to provide the first example above.

CodePudding user response:

You can define your own wrapper over json, to produce the __str__ of your requirements.
Below an example program

import json
class data:
    def __init__(self,text):
        self.text=text
    def __repr__(self):
        js=json.loads(self.text)
        string="{"
        for k in js:
            string ='"%s"=%s,'%(k,json.dumps(js[k]))
        return string[:-1] "}"
    def __str__(self):
        return self.__repr__()

line="""{"AdditionalInfo": "string",
    "AmiVersion": "string",
    "Applications": [{
                "AdditionalInfo": {
                    "string": "string"
                },
                "Args": ["string"],
                "Name": "string",
                "Version": "string"
            }]}"""
print(data(line))

Output:

{"AdditionalInfo"="string","AmiVersion"="string","Applications"=[{"AdditionalInfo": {"string": "string"}, "Args": ["string"], "Name": "string", "Version": "string"}]}
  • Related