0

I use serialize to get data in view.

contract_posts = serializers.serialize('json', Contracts.objects.all())

Then I use json.loads get data, but I just get 1 by 1 case not all data from model.

contract_posts = json.load(contract_posts)[0]
print(contract_posts["fields"])

I want to get all data, I try to use for loop but it show error

'str' object has no attribute 'read'

My for loop :

    for i in range(100):
        contract_posts = json.load(contract_posts)[i]
        print(contract_posts["fields"]["contract"])

I dont know how to get len json.load(contract_posts), so I use range 100 as an example number
Please help me all

1 Answers1

0

The error you are gettings is the result of passing a string into json.load which expects a file handle.

if you want to load a string into a dict use json.loads.

Also I would recommend you check the comment by @SivaSankar

Yuval
  • 1,202
  • 10
  • 15
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/28205792) – Amit Verma Jan 30 '21 at 18:34
  • 1
    Actually it does answer his question, he currently uses `json.load` and because of that he is getting the error – Yuval Jan 30 '21 at 18:36
  • @yuval: I agree that this is an answer. But it’s also a good learning opportunity. Your answer is not only more _useful_ with that explanation, but _also_ less likely to be mistaken as a comment or critique during review with it. I’d recommend editing your answer to include that explanation, and to be sure to expand on your reasoning when answering future questions. Even more importantly than passing review, it also helps future readers better understand your guidance. – Jeremy Caney Jan 30 '21 at 18:45
  • Pls explain this, so that other can get benefited from your answer(s). Currently, it appears more as a one-liner suggestion and without any elaboration. So, it can go as a comment to the question, unless explained considering other users from community. – Amit Verma Jan 30 '21 at 18:45