1

I am having my json like:

{
   "name": "Rahul",
   "2or4": 2,

}

Here,

How can I assign my model variable : twoOrFour to jason field value "2or4" as we can not have variable start with integer.

I am new to django. I am using dJango-rest-framework for this api.

5
  • Why not, simply, rename the JSON field 2or4 to twoOrFour? Commented May 31, 2015 at 10:18
  • actually that is not in my hand :(. Do I have any other option apart from it? Commented May 31, 2015 at 10:21
  • If you are writing backend for an API call, its better to change the API call to return "2or4" as an alias to "twoOrFour". I think you should leave the model alone Commented May 31, 2015 at 10:58
  • @Ramast: I am writing backend for API call. Can you please tell me how can I have a alias. Commented May 31, 2015 at 11:51
  • I've placed my answer below, let me know if its not clear enough Commented May 31, 2015 at 15:49

2 Answers 2

1

If you are using djangorestframework you will need to override to_representation function in your serializer

http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior

should be something like this

def to_representation(self, obj)
    serialized_data = super(SerializerClassName, self).to_representation(obj)
    serialized_data["2or4"] = serialized_data["twoOrFour"]
    //Remove the old field name
    del serialized_data["twoOrFour"]
    return serialized_data

This code should work where SerializerClassName is the class name of your serializer

Sign up to request clarification or add additional context in comments.

Comments

0

You can try adding twoOrFour to your JSON object. For example:

import json

data = {'name': 'Rahul', '2or4': 2}

data = json.loads(data) # convert to Python dict
data['twoOrFour'] = data['2or4'] # append twoOrFour
data = json.dumps(data) # convert back to JSON object

Now the JSON object has twoOrFour field. Hope it works.

Comments

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.