1

Hello I'm using python marshmallow package to convert a json file into python objects. However the one of the keys contains special character.

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)

I'm trying to convert the element "$C" into a variable. but I don't know how to deal the special character "$".

Thanks in advance.

NewbieDave
  • 1,199
  • 3
  • 12
  • 23

1 Answers1

-1

Marshmallow is not a tool for parsing json files. marshmallow is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes. source: marshmallow.readthedocs.io/en/3.0

Use json python module to load JSON.

Here is an example that demonstrates how to create and load JSON strings in Python:

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)
curusarn
  • 403
  • 4
  • 11
  • Thanks. What I'm trying to achieve is to convert the Json into python datatypes. – NewbieDave Apr 01 '19 at 18:56
  • JSON is not really a datatype, it's a serialization format. If you load JSON in python you get dict. – curusarn Apr 01 '19 at 18:59
  • To simplify. Dict is a python object. JSON is a string. You should check out this SO post: https://stackoverflow.com/questions/33169404/python-dictionary-or-json – curusarn Apr 01 '19 at 19:01
  • Correct. How do you then convert the dictionary with special character into a custom object. – NewbieDave Apr 01 '19 at 19:08
  • I'm not sure what you mean by "custom object"? Python dict handles special characters just fine. You can create it like this: `pythonDictExample = {"A":"33","$C":"12"}` and convert it to JSON like this: `jsonStringExample = json.dumps(pythonDictExample)` – curusarn Apr 01 '19 at 19:15
  • "result" in my example, is a tempASchema class. – NewbieDave Apr 01 '19 at 19:21
  • Do you really want to use the marshmallow to serialize the dictionary? What do you want to achieve by using marshmallow? – curusarn Apr 01 '19 at 19:37