【问题标题】:change numbers to strings in json dictionaries将数字更改为 json 字典中的字符串
【发布时间】:2021-05-08 00:04:32
【问题描述】:

我有一本像这样的字典:

{"first": {"phone": 1900,"other": 1}, "second": {"adwords": 1419, "no_om_source": 1223}}

我将此字典转换为 json 格式。我想将 dict 中的所有数字也更改为字符串。

 def convert(o):
        if isinstance(o, np.generic): return o.item()  
        raise TypeError

 jsonContent = json.dumps(myDict, default=convert)
    with open('data.json', 'w', encoding='utf-8') as f:
        json.dump(jsonContent, f, ensure_ascii=False, indent=4)
    return jsonContent

但是,当我尝试打印 jsonContent 时,值仍然是数字而不是字符串。我该如何更改?

【问题讨论】:

    标签: python json python-3.x numpy dictionary


    【解决方案1】:

    在将您的 dict 转换为 json 格式之前尝试一下。

    myDict = {"first": {"phone": 1900,"other": 1}, "second": {"adwords": 1419, "no_om_source": 1223}}
    for x in myDict:
        for k,v in myDict[x].items():
            myDict[x][k] = str(v)
    

    输出

    {'first': {'phone': '1900', 'other': '1'}, 'second': {'adwords': '1419', 'no_om_source': '1223'}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      • 2014-07-06
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多