Home > Net >  Add json response to a list
Add json response to a list

Time:03-31

I am new in learning python requests and I am using GET METHOD and I am trying to insert returned json content in list, But it is showing

TypeError: Object of type bytes is not JSON serializable

I have tried many times and I also tried by adding into dictionary.

views.py

def request_get(request):
    url = "http://127.0.0.1:8000/api/items/"
    response = requests.get(url)

    results = []

    results.append(response.content)

    return redirect('home')

But it is showing TypeError: Object of type bytes is not JSON serializable

I have also tried by using :-

results = []

results.append({
    'response' : response.content
})

Full Traceback

Traceback (most recent call last):
  File "D:\apps - app\app\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "D:\apps - app\app\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\app - app - app\env\lib\site-packages\django\http\response.py", line 653, in __init__
    data = json.dumps(data, cls=encoder, **json_dumps_params)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "D:\app - app - app\env\lib\site-packages\django\core\serializers\json.py", line 106, in default
    return super().default(o)
  File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable

But it also didn't worked for me.

Any help would be much Appreciated. Thank You in Advance

CodePudding user response:

You need to use results.append(response.json()) to convert to JSON


Or try:

import json
results.append(json.loads(response.content.decode("utf-8")))
  • Related