0

I have a python script that should generate a json file in a specific structure.

So to achieve that, my plan was to create my entity data classes that represents the structure of this json file, construct them, do all the magic needed for generation, and dump my object into a json file with json.dumps(my_object).

Now my problem is that this json structure have fields like weird-field:. since I can't use the "dash" symbol in my dataclass because of python syntax, I can't create my entity class that represents my json structure. (This json file will be used by another system, so I have no way to change the structure.)

Right now I worked around it by using wrong field names like weird_field that are accepted by python, then after encoding them to json I manually replaced those wrong field names in the json string.

I wonder if there is a better way to do it. In java you can just use a special annotation on those fields in your class to say "Hey Jackson, use this string for encoding instead of the name of the class' field". What's the python way to do the same?

In code what I'd like to do is:

@dataclass
class MyClass:
   weird-field: int = 0  # syntax error here 


json_obj = MyClass()
json_obj.weird-field = 621
print(json.dumps(json_obj))

I'd like to get

{
  weird-field: 621
}

But it crashes since '-' can't be used for field name in python.

2
  • Do your own parse function and write yourself your desired JSON output Commented Mar 29, 2019 at 10:32
  • That seems like a lot of work. My json is a lot bigger than this example with a lot of subclasses. I'd rather use some easier solution. Commented Mar 29, 2019 at 12:17

1 Answer 1

1

Use dictionaries.

json_obj = dict()

json_obj['weird-field'] = 621

my_weird_value = json_obj['weird-field'] # returns 621

print(json.dumps(json_obj))
Sign up to request clarification or add additional context in comments.

1 Comment

This can work, however I don't like the fact I can't use predefined classes. The json structure has a list of subclasses for example, and every time I want to append this list, I need to create a new dictionary and make every key by hand, giving me a lot of chance to make typing errors. But I guess I can just keep my classes, create a function that makes a dictionary of itself with the right keys, and work with that. So thanks, I can work with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.