[英]python read file and output into format string
I have a sample json file example below我在下面有一个示例 json 文件示例
{
"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';并希望转换为如下示例的格式化字符串,它将转换为公共 static XX= 'yy';
Where XX is the Upper case of yy其中 XX 是 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)
You can make use of the json
module to parse the JSON file in Python like I did below:您可以使用
json
模块来解析 Python 中的 JSON 文件,如下所示:
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: 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';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.