【问题标题】:Python parse Json with key with special characterPython用带有特殊字符的键解析Json
【发布时间】:2019-04-01 18:38:17
【问题描述】:

您好,我正在使用 python marshmallow 包将 json 文件转换为 python 对象。但是其中一个键包含特殊字符。

from marshmallow import Schema

fakeJson = {"A":"33","$C":"12"}

class tempA:
    def __init__(self,
                 A = None):
        self.A = A

class tempASchema(Schema):
    model = tempA
    A = fields.Str()

result=tempASchema().load(fakeJson)

我正在尝试将元素“$C”转换为变量。但我不知道如何处理特殊字符“$”。

提前致谢。

【问题讨论】:

  • 您遇到错误了吗?到底是什么问题?
  • json 支持...请追溯/错误
  • Marshmallow 不是解析 json 文件的工具。 marshmallow is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes. 来源:marshmallow.readthedocs.io/en/3.0
  • @aws_apprentice 我没有收到任何错误。我只想将“$C”转换为变量。但不知道如何在那里处理“$”。
  • 变量名中不能有美元符号

标签: python marshmallow


【解决方案1】:

Marshmallow 不是解析 json 文件的工具。 marshmallow is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes. 来源:marshmallow.readthedocs.io/en/3.0

使用jsonpython模块加载JSON。

这是一个示例,演示如何在 Python 中创建和加载 JSON 字符串:

import json

# this is how you create a dict object in python
pythonDictExample = {"A":"33","$C":"12"}

# this is how to create a json string from python dict
jsonExample = json.dumps(pythonDictExample)

print("Printing json string")
print(jsonExample)

# this is how you load a json string into a python dict
loadedPythonDict = json.loads(jsonExample)

print("Printing dict (loaded json string)")
print(loadedPythonDict)

【讨论】:

  • 谢谢。我想要实现的是将 Json 转换为 python 数据类型。
  • JSON 并不是真正的数据类型,它是一种序列化格式。如果你在 python 中加载 JSON,你会得到 dict。
  • 为了简化。字典是一个python对象。 JSON 是一个字符串。你应该看看这个 SO 帖子:stackoverflow.com/questions/33169404/python-dictionary-or-json
  • 正确。然后如何将具有特殊字符的字典转换为自定义对象。
  • 我不确定您所说的“自定义对象”是什么意思? Python dict 可以很好地处理特殊字符。您可以这样创建它:pythonDictExample = {"A":"33","$C":"12"} 并将其转换为 JSON,如下所示:jsonStringExample = json.dumps(pythonDictExample)
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 2011-08-21
  • 2012-04-22
  • 2018-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多