0

I have a sample json file example below

    {
      "email": "string",
      "cont_pic": "string",
      "title": "string",
      "user_cd": "string",
      "type4": "string"
    }

and want to convert into a formatted string like example below , it will convert into public static XX= 'yy';
Where XX is the Upper case of yy

  public static EMAIL= 'email';
  public static CONTACT_PIC = 'cont_pic';
  public static TITLE = 'title';
  public static USER_CODE = 'user_cd';
  public static TYPE4 = 'type4';

I have stuck at below code

filename = "file.json"
with open(filename) as f:
    contents = f.read()
    contents = contents.split(':')
    print(contents)
2
  • what would yy be though Commented Apr 25, 2021 at 5:21
  • 1
    this is not a textfile so you can't parse it with just f.read() ! you should parse json i recommend you to study about json in python first. check below link : w3schools.com/python/python_json.asp Commented Apr 25, 2021 at 5:22

1 Answer 1

1

You can make use of the json module to parse the JSON file in Python like I did below:

import json

with open("file.json", "r") as f:
    data = json.loads(f.read())

    for key in data:
        print(f"public static {key.upper()} = '{key}';")

Output:

public static EMAIL = 'email';
public static CONT_PIC = 'cont_pic';
public static TITLE = 'title';
public static USER_CD = 'user_cd';
public static TYPE4 = 'type4';
Sign up to request clarification or add additional context in comments.

2 Comments

this work great! if I have a json field like "serviceChanged": true, how can I based on the camel case to convert it become public static SERVICE_CHANGED= 'serviceChanged';
@B.Cos If my answer solved your problem please click on the checkmark next to my answer. Please post your question about the camel case as a separate question so that it will be easier for people with the same problem in the future, to find the answer quickly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.