Home > OS >  How to convert Json format to Python format with appropriate types instead of values
How to convert Json format to Python format with appropriate types instead of values

Time:10-25

Can you please advice some library / any other tool or python code to convert Json format to Python format with appropriate types instead of values

Given (JSON format):

 {
        "data": {
            "id": 8,
            "email": "[email protected]",
            "first_name": "Agent",
            "last_name": "J",
            "avatar": "image.jpg"
        },
        "support": {
            "url": "https://test.com/#support-heading",
            "text": "I’m an agent, but I’m from the future!"
        }
    }

Expected (Python format types instead of values):

{
        "data": {
            "id": int,
            "email": str,
            "first_name": str,
            "last_name": str,
            "avatar": str,
        },
        "support": {
            "url": str,
            "text": str,
        }
    }

CodePudding user response:

After fixing the mistakes in your JSON, this does what you asked. Note that this does not handle arbitrarily deep nesting; if you have nested objects, then first you have to decide whether you want to use "dict" or dive into them. If you do want to dive into them, then you'd need to make this recursive.

import json
data = '''
{
    "data": {
        "id": 8,
        "email": "[email protected]",
        "first_name": "Agent",
        "last_name": "J",
        "avatar": "image.jpg"
    },
    "support": {
        "url": "https://test.com/#support-heading",
        "text": "I'm an agent, but I'm from the future!"
    }
}'''

data = json.loads(data)
for k,v in data.items():
    for k1,v1 in v.items():
        v[k1] = type(v1)

from pprint import pprint
pprint(data)

Output:

{'data': {'avatar': <class 'str'>,
          'email': <class 'str'>,
          'first_name': <class 'str'>,
          'id': <class 'int'>,
          'last_name': <class 'str'>},
 'support': {'text': <class 'str'>, 'url': <class 'str'>}}

CodePudding user response:

I know it's not very convenient, but you could go through all of the classes you need converted using a for loop.

import json

with open('data.json') as f:
    data = json.load(f)
    for x in data:
        int(x["data"]["id"])

CodePudding user response:

If you're using VSCode you can use the Paste JSON as Code extension.

Simply install the extension then type Ctrl Shift P (Cmd Shift P on MacOS) and type "Paste JSON as Code".

The Python code will be generated based on your clipboard contents.

  • Related