如何修改json文件中的value值并保存至文件?

问题:

  • 在原json文件的基础上仅针对所有value值进行替换并保存文件(PS:value值中存在的字符类型有:int,bool,str,float。这里仅仅针对str字符类型进行替换,其他类型跳过不做处理。)

json范例:

{
        "squadName" : "SUPER HERO SQUAD",
        "homeTown" : "METRO CITY",
        "formed" : 2016,
        "secretBase" : "SUPER TOWER",
        "active" : true,
        "members" : [
            {
                "name" : "MOLECULE MAN",
                "age" : 29.3,
                "secretIdentity" : "DAN JUKES",
                "powers" : [
                    "RADIATION RESISTANCE",
                    "TURNING TINY",
                    "RADIATION BLAST"
                ]
            },
            {
                "name" : "MADAME UPPERCUT",
                "age" : 39,
                "secretIdentity" : "JANE WILSON",
                "powers" : [
                    "MILLION TONNE PUNCH",
                    "DAMAGE RESISTANCE",
                    "SUPERHUMAN REFLEXES"
                ]
            },
            {
                "name" : "ETERNAL FLAME",
                "age" : 1000000,
                "secretIdentity" : "UNKNOWN",
                "powers" : [
                    "IMMORTALITY",
                    "HEAT IMMUNITY",
                    "INFERNO",
                    "TELEPORTATION",
                    "INTERDIMENSIONAL TRAVEL"
                ]
            }
        ]
    }

Code:

import requests
import json
import time

def translate(words):
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
    # 传输的参数,其中 i 为需要翻译的内容
    # word = '\n'.join(words)
    key = {
        'i': words,
        'from': 'en',
        'to': 'zh-CHS',
        'smartresult': 'dict',
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTlME'
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
    }
    # key 这个字典为发送给有道词典服务器的内容
    response = requests.post(url, data=key, headers=headers)
    # 判断服务器是否相应成功
    if response.status_code == 200:
        # 然后相应的结果
        result = json.loads(response.text)
        # print(result)
        # print([item[0]['tgt'] for item in result['translateResult']])
        return [item[0]['tgt'] for item in result['translateResult']]

    else:
        print("有道词典调用失败")
        # 相应失败就返回空
        return None


def jsonText():
    with open('/Users/scrooge/Desktop/json翻译/aa.json', 'r') as f:
        readText = f.read()
        return readText


def convert(var):
    if isinstance(var, dict):
        return {key:convert(value) for key, value in var.items()}
    elif isinstance(var, list):
        return [convert(item) for item in var]
    elif isinstance(var, tuple):
        return (convert(item) for item in var)
    elif isinstance(var, str):
        # # print(type(translate(var)))
        # var = translate(var)
        # var = str(var)
        # print(type(var))
        # # time.sleep(0.5)
        return translate(var)
    else:
        return var

json_text = jsonText()

var = json.loads(json_text)
new_var = convert(var)

with open('ss.json', 'wt') as f:
    json.dump(new_var, f, ensure_ascii=False)

输出:

{
    "squadName":[
        "超级英雄的队伍"
    ],
    "homeTown":[
        "地铁的城市"
    ],
    "formed":2016,
    "secretBase":[
        "超级塔"
    ],
    "active":true,
    "members":[
        {
            "name":[
                "分子的人"
            ],
            "age":29,
            "secretIdentity":[
                "丹朱克斯"
            ],
            "powers":[
                [
                    "辐射电阻"
                ],
                [
                    "把小"
                ],
                [
                    "辐射爆炸"
                ]
            ]
        },
        {
            "name":[
                "夫人上钩拳"
            ],
            "age":39,
            "secretIdentity":[
                "简·威尔逊"
            ],
            "powers":[
                [
                    "几百万吨冲床"
                ],
                [
                    "伤害抵抗"
                ],
                [
                    "超人的反应"
                ]
            ]
        },
        {
            "name":[
                "永恒的火焰"
            ],
            "age":1000000,
            "secretIdentity":[
                "未知的"
            ],
            "powers":[
                [
                    "永生"
                ],
                [
                    "热的免疫力"
                ],
                [
                    "INFERNO"
                ],
                [
                    "传送"
                ],
                [
                    "多维交互旅行"
                ]
            ]
        }
    ]
}

遇到的问题:

  • 字符串类型转换和进行io读写报错
  • 拿到的json数据不能直接使用replace()方法
讨论数量: 9
Jason990420

这是使用 isinstance 函数, 以及递归的方式

def translate(string):
    return string.lower()

def convert(var):
    if isinstance(var, dict):
        return {key:convert(value) for key, value in var.items()}
    elif isinstance(var, list):
        return [convert(item) for item in var]
    elif isinstance(var, tuple):
        return (convert(item) for item in var)
    elif isinstance(var, str):
        return translate(var)
    else:
        return var

var = json.loads(json_txt)
new_var = convert(var)

with open(filename, 'wt') as f:
    json.dump(var, f, ensure_ascii=False)

注: 如果 ensure_ascii 为 False,那么写入 fp 的字符串可以包含非 ASCII 字符; 否则,所有此类字符都会在 JSON 字符串中转义。(缺省为 True)

>>> new_var
{'active': True,
 'formed': 2016,
 'homeTown': 'metro city',
 'members': [{'age': 29.3,
              'name': 'molecule man',
              'powers': ['radiation resistance',
                         'turning tiny',
                         'radiation blast'],
              'secretIdentity': 'dan jukes'},
             {'age': 39,
              'name': 'madame uppercut',
              'powers': ['million tonne punch',
                         'damage resistance',
                         'superhuman reflexes'],
              'secretIdentity': 'jane wilson'},
             {'age': 1000000,
              'name': 'eternal flame',
              'powers': ['immortality',
                         'heat immunity',
                         'inferno',
                         'teleportation',
                         'interdimensional travel'],
              'secretIdentity': 'unknown'}],
 'secretBase': 'super tower',
 'squadName': 'super hero squad'}
1周前 评论
Scrooge (楼主) 1周前
Jason990420 (作者) 1周前
Scrooge (楼主) 1周前
Scrooge (楼主) 1周前
Jason990420 (作者) 1周前
Scrooge (楼主) 1周前
Jason990420 (作者) 1周前
Jason990420

没任何回应, 也没打钩 ? 这个问题解决了吗 ?

6天前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!