0

I am new to python and django. i must consume a web service and the response of web service is json like this:

[{'name': 'gfile1.txt', 'length': 448, 'createdDate': '1582229671352'}, {'name': 'gfile2.txt', 'length': 86, 'createdDate': '1582229671474'}, {'name': 'soc-LiveJournal1.txt', 'length': 1080598042, 'createdDate': '1582229715227'}]

also i have a class according to this json result: the below is class definition:

class DataParameter:
    def __init__(self, name, size, _createdDate):
        self.filename = name
        self.filesize = size
        self.createdDate = _createdDate

what should i do is: i must convert the above json to list of DataParameter class. Can you help me to do this? Thanks

3
  • Are you using django-rest-framework? Commented Mar 6, 2020 at 13:07
  • yes the json is the result of request.get(url): Commented Mar 6, 2020 at 13:09
  • why not use DRF parser django-rest-framework.org/api-guide/parsers/… Commented Mar 6, 2020 at 13:21

2 Answers 2

1

If I understand you correctly, you can try something like this:

data = [
    {'name': 'gfile1.txt', 'length': 448, 'createdDate': '1582229671352'},
    {'name': 'gfile2.txt', 'length': 86, 'createdDate': '1582229671474'},
    {'name': 'soc-LiveJournal1.txt', 'length': 1080598042, 'createdDate': '1582229715227'}
]


class DataParameter:
    def __init__(self, name, size, _createdDate):
        self.filename = name
        self.filesize = size
        self.createdDate = _createdDate


new_list = []

for i in data:
    new_list.append(DataParameter(i['name'], i['length'], i['createdDate']))

print(new_list)
Sign up to request clarification or add additional context in comments.

Comments

0

Here's a quick and dirty alternative

class DataParameter:
    def __init__(self, name, size, _createdDate):
        self.filename = name
        self.filesize = size
        self.createdDate = _createdDate

    @classmethod
    def from_json(cls, json_str):
        lst = []
        for dct in json:
            lst.append(cls(**json_dict))
        return lst

#Usage 
my_json = [{'name': 'gfile1.txt', 'length': 448, 'createdDate': '1582229671352'}, {'name': 'gfile2.txt', 'length': 86, 'createdDate': '1582229671474'}, {'name': 'soc-LiveJournal1.txt', 'length': 1080598042, 'createdDate': '1582229715227'}]
DataParameter.from_json(my_json)

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.