I am using django-restframework, I use postman POST json data to my project but I got the error like tittle, I have set raw and application/json here is the code from postman.
POST /account/post/reply/ HTTP/1.1
Host: localhost:8000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: a0c7bd93-631e-4c7a-8106-87f018eaf7da
{
"user": "michael",
"userid": "1",
"ihelpid": 6,
"tittle": "6",
"info": "6",
"label": "3",
"tel": "dxy970525",
"picture1": null,
"picture2": null
}
my code is really easy only like :
from rest_framework.parsers import JSONParser,ParseError
class ReplyViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list` and `detail` actions.
"""
pagination_class=PageNumberPagination
queryset = Forum_reply.objects.all()
serializer_class = ReplySerializer
#filter
filter_backends = (DjangoFilterBackend, )
filter_fields = ['postID',]
def create(self, request, *args, **kwargs):
print(request.data)
data = JSONParser().parse(request)
return HttpResponse("ok")
After I use viewsets,this error occur,I have print it on shell but it is no problem
Содержание
- JSONDecodeError: Expecting value: line 1 column 1 (char 0)
- JSONDecodeError: Expecting value: line 1 column 1 (char 0)
- Example JSONDecodeError: Expecting value: line 1 column 1 (char 0)
- Solution
- Other Possible Solutions
- Ensure HTTP 200 status code and valid content type as application/json
- From Expecting value: line 1 column 1 (char 0) to Response content not in json format #4908
- Comments
- System Information
- Бот выдает ошибку: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). как исправить?
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Table of Contents Hide
If you are working with APIs and trying to fetch and parse the JSON data while making the HTTP or curl requests and JSON response is not well-formed, Python will throw json.decoder.jsondecodeerror: expecting value: line 1 column 1 (char 0).
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Let us take a look at the possible causes of JSONDecodeError and how we solve this issue in our code with some examples.
In most of cases, you get json.loads- JSONDecodeError: Expecting value: line 1 column 1 (char 0) error is due to :
- The response might be in some other format such as XML, HTML, etc.
- The JSON response is not structured properly.
- The response type doesn’t come in the format of application/json. Rather it comes in string format, which in turn throws a JSONDecodeError while parsing the response.
- Empty response
- Invalid status code or httpx error
Also, read the Python JSONPath tutorial
Example JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Let me demonstrate with a simple example of replicating a JSONDecodeError, and we will look at solving the same.
In this example, we are trying to load a JSON file from the specified path and print the contents of the JSON file. However, since the JSON file is empty, the JSON module will throw a JSONDecodeError when we try to read the empty content. It always expects the proper JSON structure.
Output
The json.loads(j.read()) tries to load the JSON content and parse the JSON, and during that time, if it’s not well structured, you get a JSONDecodeError.
Note: In this case, if the JSON file is not found, you will get a FileNotFoundError: [Errno 2] No such file or directory
Solution
The solution is simple and straightforward. Validate if the file is not empty and has proper JSON content. Now that we have added the proper content to the books.json file when we run the same code again, we get the below output.
Output
Other Possible Solutions
Ensure HTTP 200 status code and valid content type as application/json
If you are making requests to API, make sure to check the response status code is 200 (OK) and then perform JSON parse. Below is the sample snippet on how you can ensure to check the response has 200 status code and valid content type as application/json
Источник
From Expecting value: line 1 column 1 (char 0) to Response content not in json format #4908
I do not think it is informative and maybe it could contain something like:
Json: Response content is not in the json format
Do you think it is a good idea to wrap line 892 of requests/models.py into something like:
System Information
The text was updated successfully, but these errors were encountered:
If you inspect the response headers, it’s not returning JSON so you shouldn’t be unconditionally calling .json() on the response.
Thanks for the quick reply!
You solved my problem!
For future reference, below how to get the JSON content or to get some spam:
Thanks for the quick reply!
You solved my problem!
For future reference, below how to get the JSON content or to get some spam:
unfortunately not all systems that return json set the Content-Type correctly
The best way to handle this is catch the JSONDecodeError:
p.s. JSONDecodeError: Expecting value: line 1 column 1 (char 0) specifically happens with an empty string (i.e. empty response content)
p.s. JSONDecodeError: Expecting value: line 1 column 1 (char 0) specifically happens with an empty string (i.e. empty response content)
Not specifically. As the name suggests, it’s a decoding error:
To check whether it’s an empty response you can look at the exception’s doc attribute:
I know, I meant that the specific position line 1 column 1 (char 0) happens in the case there is an empty string
Not necessarily. In my previous comment there is an example of the opposite.
The line x column y (char z) only shows where the invalid starting value for an expected object was found or, if it’s the case, not found.
In addition to empty responses, the line 1 column 1 (char 0) also often means that the document is in another format (such as XML or HTML, as in my first comment).
That’s why I believe the op’s request would clearly be useful. That’s a significant difference.
Источник
Бот выдает ошибку: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). как исправить?
У меня есть вот такой код
r = requests.post(KERAS_REST_API_URL, files=payload).json()
2020-02-27 15:41:14,292 (util.py:66 WorkerThread1) ERROR — TeleBot: «JSONDecodeError occurred, args=(‘Expecting value: line 1 column 1 (char 0)’,)
Traceback (most recent call last):
File «C:Python37libsite-packagestelebotutil.py», line 60, in run
task(*args, **kwargs)
File «C:UsersuserDesktopbotbottbot.py», line 55, in answer_photo
r = requests.post(KERAS_REST_API_URL, files=payload).json()
File «C:Python37libsite-packagesrequestsmodels.py», line 898, in json
return complexjson.loads(self.text, **kwargs)
File «C:Python37libjson__init__.py», line 348, in loads
return _default_decoder.decode(s)
File «C:Python37libjsondecoder.py», line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File «C:Python37libjsondecoder.py», line 355, in raw_decode
raise JSONDecodeError(«Expecting value», s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
»
Traceback (most recent call last):
File «C:UsersuserDesktopbotbottbot.py», line 92, in
bot.polling(none_stop=True)
File «C:Python37libsite-packagestelebot__init__.py», line 392, in polling
self.__threaded_polling(none_stop, interval, timeout)
File «C:Python37libsite-packagestelebot__init__.py», line 416, in __threaded_polling
self.worker_pool.raise_exceptions()
File «C:Python37libsite-packagestelebotutil.py», line 109, in raise_exceptions
six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
File «C:Python37libsite-packagessix.py», line 703, in reraise
raise value
File «C:Python37libsite-packagestelebotutil.py», line 60, in run
task(*args, **kwargs)
File «C:UsersuserDesktopbotbottbot.py», line 55, in answer_photo
r = requests.post(KERAS_REST_API_URL, files=payload).json()
File «C:Python37libsite-packagesrequestsmodels.py», line 898, in json
return complexjson.loads(self.text, **kwargs)
File «C:Python37libjson__init__.py», line 348, in loads
return _default_decoder.decode(s)
File «C:Python37libjsondecoder.py», line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File «C:Python37libjsondecoder.py», line 355, in raw_decode
raise JSONDecodeError(«Expecting value», s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
- Вопрос задан более двух лет назад
- 15421 просмотр
Простой 2 комментария
500 Internal Server Error
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
AttributeError: ‘_thread._local’ object has no attribute ‘value’
И посмотреть что оно возвращает. Быстрее всего там не json, а текст ошибки
З.Ы. В остальной код не вникал
500 Internal Server Error
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
AttributeError: ‘_thread._local’ object has no attribute ‘value’
C:WINDOWSsystem32>python C:UsersuserDesktopsimple-keras-rest-api-mastersimple-keras-rest-api-masterrun_keras_server.py
Using TensorFlow backend.
2020-02-27 17:22:58.468183: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library ‘cudart64_101.dll’; dlerror: cudart64_101.dll not found
2020-02-27 17:22:58.474047: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
* Loading Keras model and Flask starting server. please wait until server has fully started
2020-02-27 17:23:14.418136: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library nvcuda.dll
2020-02-27 17:23:15.076804: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1555] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GT 525M computeCapability: 2.1
coreClock: 1.2GHz coreCount: 2 deviceMemorySize: 1.00GiB deviceMemoryBandwidth: 26.82GiB/s
2020-02-27 17:23:15.089234: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library ‘cudart64_101.dll’; dlerror: cudart64_101.dll not found
2020-02-27 17:23:15.099531: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library ‘cublas64_10.dll’; dlerror: cublas64_10.dll not found
2020-02-27 17:23:15.109041: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library ‘cufft64_10.dll’; dlerror: cufft64_10.dll not found
2020-02-27 17:23:15.118869: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library ‘curand64_10.dll’; dlerror: curand64_10.dll not found
2020-02-27 17:23:15.127996: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library ‘cusolver64_10.dll’; dlerror: cusolver64_10.dll not found
2020-02-27 17:23:15.137769: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library ‘cusparse64_10.dll’; dlerror: cusparse64_10.dll not found
2020-02-27 17:23:15.147974: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library ‘cudnn64_7.dll’; dlerror: cudnn64_7.dll not found
2020-02-27 17:23:15.153373: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1592] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices.
2020-02-27 17:23:15.168159: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1096] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-02-27 17:23:15.172543: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1102]
* Serving Flask app «run_keras_server» (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on 127.0.0.1:5000 (Press CTRL+C to quit)
[2020-02-27 17:25:35,908] ERROR in app: Exception on /predict [POST]
Traceback (most recent call last):
File «C:Python37libsite-packagesflaskapp.py», line 2446, in wsgi_app
response = self.full_dispatch_request()
File «C:Python37libsite-packagesflaskapp.py», line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File «C:Python37libsite-packagesflaskapp.py», line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File «C:Python37libsite-packagesflask_compat.py», line 39, in reraise
raise value
File «C:Python37libsite-packagesflaskapp.py», line 1949, in full_dispatch_request
rv = self.dispatch_request()
File «C:Python37libsite-packagesflaskapp.py», line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File «C:UsersadmwiDesktopsimple-keras-rest-api-mastersimple-keras-rest-api-masterrun_keras_server.py», line 61, in predict
preds = model.predict(image)
File «C:Python37libsite-packageskerasenginetraining.py», line 1452, in predict
if self._uses_dynamic_learning_phase():
File «C:Python37libsite-packageskerasenginetraining.py», line 382, in _uses_dynamic_learning_phase
not isinstance(K.learning_phase(), int))
File «C:Python37libsite-packageskerasbackendtensorflow_backend.py», line 73, in symbolic_fn_wrapper
if _SYMBOLIC_SCOPE.value:
AttributeError: ‘_thread._local’ object has no attribute ‘value’
127.0.0.1 — — [27/Feb/2020 17:25:35] «[35m[1mPOST /predict HTTP/1.1[0m» 500 —
По идеи код должен обрабатывать изображение с помощью нейронной сети модифицируя его и после выводить результат в сообщении в таком формате
Источник
If you try to parse invalid JSON or decode an empty string as JSON, you will encounter the JSONDecodeError: Expecting value: line 1 column 1 (char 0). This error can occur if you read an empty file using json.load, read an empty JSON or receive an empty response from an API call.
You can use a try-except code block to catch the error and then check the contents of the JSON string or file before retrying.
This tutorial will go through the error in detail and how to solve it with code examples.
Table of contents
- JSONDecodeError: Expecting value: line 1 column 1 (char 0)
- Example #1: Incorrect use of json.loads()
- Solution
- Example #2: Empty JSON file
- Solution
- Example #3: Response Request
- Summary
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
In Python, JSONDecodeError occurs when there is an issue with the formatting of the JSON data. This specific error tells us the JSON decoder has encountered an empty JSON.
Example #1: Incorrect use of json.loads()
Let’s look at an example where we have a JSON file with the following contents:
[ {"margherita":7.99}, {"pepperoni":9.99}, {"four cheeses":10.99} ]
We want to read the data into a program using the json
library. Let’s look at the code:
import json json_path = 'pizza.json' data = json.loads(json_path)
In the above code, we try to read the data in using json.loads()
. Let’s run the code to see the result:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The error occurs because json.loads()
expects a JSON encoded string, not a filename. The string pizza.json
is not a valid JSON encoded string.
Solution
We need to use json.load()
instead of json.loads()
to read a file. Let’s look at the revised code:
import json json_path = 'pizza.json' with open(json_path, 'r') as f: data = json.loads(f.read()) print(data)
In the above code, we use the open()
function to create a file object that json.load()
can read and return the decoded data object. The with
statement is a context manager that ensures that the file is closed once the code is complete. Let’s run the code to see the result:
[{'margherita': 7.99}, {'pepperoni': 9.99}, {'four cheeses': 10.99}]
Example #2: Empty JSON file
Let’s look at an example where we have an empty file, which we will try to read in using json.loads()
. The file is called particles.json
. Since the JSON file is empty, the JSON decoder will throw the JSONDecodeError when it tries to read the file’s contents. Let’s look at the code:
import json filename = 'particles.json' with open(filename, 'r') as f: contents = json.loads(f.read()) print(contents)
--------------------------------------------------------------------------- JSONDecodeError Traceback (most recent call last) Input In [1], in <cell line: 5>() 3 filename = 'particles.json' 5 with open(filename, 'r') as f: ----> 6 contents = json.loads(f.read()) 7 print(contents) File ~/opt/anaconda3/lib/python3.8/json/__init__.py:357, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 352 del kw['encoding'] 354 if (cls is None and object_hook is None and 355 parse_int is None and parse_float is None and 356 parse_constant is None and object_pairs_hook is None and not kw): --> 357 return _default_decoder.decode(s) 358 if cls is None: 359 cls = JSONDecoder File ~/opt/anaconda3/lib/python3.8/json/decoder.py:337, in JSONDecoder.decode(self, s, _w) 332 def decode(self, s, _w=WHITESPACE.match): 333 """Return the Python representation of ``s`` (a ``str`` instance 334 containing a JSON document). 335 336 """ --> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 338 end = _w(s, end).end() 339 if end != len(s): File ~/opt/anaconda3/lib/python3.8/json/decoder.py:355, in JSONDecoder.raw_decode(self, s, idx) 353 obj, end = self.scan_once(s, idx) 354 except StopIteration as err: --> 355 raise JSONDecodeError("Expecting value", s, err.value) from None 356 return obj, end JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Solution
If the file is empty, it is good practice to add a try-except statement to catch the JSONDecodeError. Let’s look at the code:
import json filename = 'particles.json' with open(filename, 'r') as f: try: contents = json.loads(f.read()) print(contents) except json.decoder.JSONDecodeError: print('File is empty')
File is empty
Now we have verified the file is empty, we can add some content to the file. We will add three particle names together with their masses.
[ {"proton":938.3}, {"neutron":939.6}, {"electron":0.51} ]
Let’s try to read the JSON file into our program and print the contents to the console:
import json filename = 'particles.json' with open(filename, 'r') as f: try: contents = json.loads(f.read()) print(contents) except json.decoder.JSONDecodeError: print('File is empty')
[{'proton': 938.3}, {'neutron': 939.6}, {'electron': 0.51}]
We successfully read the contents of the file into a list object.
Example #3: Response Request
Let’s look at an example where we want to parse a JSON response using the requests library. We will send a RESTful GET call to a server, and in return, we get a response in JSON format. The requests library has a built-in JSON decoder, response.json(), which provides the payload data in the JSON serialized format.
We may encounter a response that has an error status code or is not content-type application/json
. We must check that the response status code is 200 (OK) before performing the JSON parse. Let’s look at the code to check the response has the 200
status code and has the valid content type. application/json
.
import requests from requests.exceptions import HTTPError url = 'https://httpbin.org/get' try: response = requests.get(url) status = response.status_code if (status != 204 and response.headers["content-type"].strip().startswith("application/json")): try: json_response = response.json() print(json_response) except ValueError: print('Bad Data from Server. Response content is not valid JSON') elif (status != 204): try: print(response.text) except ValueError: print('Bad Data From Server. Reponse content is not valid text') except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except Exception as err: print(f'Other error occurred: {err}')
In the above example, we use httpbin.org to execute a GET call. Let’s run the code to get the result:
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.27.1', 'X-Amzn-Trace-Id': 'Root=1-6265a5c1-3b57327c02057a3a39ffe86d'}, 'origin': '90.206.95.191', 'url': 'https://httpbin.org/get'}
Summary
Congratulations on reading to the end of this tutorial! The JSONDecodeError: Expecting value: line 1 column 1 (char 0) occurs either when data is not present in a file, the JSON string is empty, or the payload from a RESTful call is empty.
You can resolve this error by checking the JSON file or string for valid content and using an if-statement when making a RESTful call to ensure the status code is 200 and the content type is application/json
.
For further reading on errors involving JSON, go to the articles:
- How to Solve Python ValueError: Trailing data
- How to Solve Python JSONDecodeError: extra data
- How to Solve Python TypeError: Object of type datetime is not JSON serializable
- How to Solve Python JSONDecodeError: Expecting ‘,’ delimiter: line 1
Have fun and happy researching!
From Expecting value: line 1 column 1 (char 0) to Response content not in json format #4908
Comments
SebastianoF commented Dec 13, 2018 •
I do not think it is informative and maybe it could contain something like:
Json: Response content is not in the json format
Do you think it is a good idea to wrap line 892 of requests/models.py into something like:
System Information
The text was updated successfully, but these errors were encountered:
sigmavirus24 commented Dec 13, 2018
If you inspect the response headers, it’s not returning JSON so you shouldn’t be unconditionally calling .json() on the response.
SebastianoF commented Dec 13, 2018 •
Thanks for the quick reply!
You solved my problem!
For future reference, below how to get the JSON content or to get some spam:
wesinator commented May 12, 2020
Thanks for the quick reply!
You solved my problem!
For future reference, below how to get the JSON content or to get some spam:
unfortunately not all systems that return json set the Content-Type correctly
The best way to handle this is catch the JSONDecodeError:
p.s. JSONDecodeError: Expecting value: line 1 column 1 (char 0) specifically happens with an empty string (i.e. empty response content)
nuno-andre commented Sep 24, 2020
p.s. JSONDecodeError: Expecting value: line 1 column 1 (char 0) specifically happens with an empty string (i.e. empty response content)
Not specifically. As the name suggests, it’s a decoding error:
To check whether it’s an empty response you can look at the exception’s doc attribute:
wesinator commented Sep 24, 2020
I know, I meant that the specific position line 1 column 1 (char 0) happens in the case there is an empty string
nuno-andre commented Sep 24, 2020 •
Not necessarily. In my previous comment there is an example of the opposite.
The line x column y (char z) only shows where the invalid starting value for an expected object was found or, if it’s the case, not found.
In addition to empty responses, the line 1 column 1 (char 0) also often means that the document is in another format (such as XML or HTML, as in my first comment).
That’s why I believe the op’s request would clearly be useful. That’s a significant difference.
Источник
[Fixed] JSONDecodeError: Expecting Value: Line 1 column 1 (char 0)
JSONDecodeError: Expecting value: line 1 column 1 (char 0) occurs while working with JSON (JavaScript Object Notation) format. You might be storing some data or trying to fetch JSON data from an API(Application Programming Interface). In this guide, we will discuss where it can creep in and how to resolve it.
How can JSONDecodeError: Expecting value: line 1 column 1 (char 0) occur?
JSONDecodeError means there is an incorrect JSON format being followed. For instance, the JSON data may be missing a curly bracket, have a key that does not have a value, and data not enclosed within double-quotes or some other syntactic error.
Generally, the error expecting value: line 1 column 1 (char 0) error can occur due to the following reasons.
- Non-JSON conforming quoting
- Empty JSON file
- XML output (that is, a string starting with 1. Non-JSON conforming quoting
JSON or JavaScript Object Notation has a similar format to that of the python dictionary datatype. A dictionary requires a key or value to be enclosed in quotes if it is a string. Similarly, the JSON standard defines that keys need not be a string. However, keys should always be enclosed within double quotes. Not following this standard can also raise an error.
2. Empty JSON file
For this example, we have taken an empty JSON file named test.py and another file named test.py, which contains the code given below. Using context manager, we open the JSON file in reading mode and load it using the load method. However, an error is thrown because the JSON file is empty.
3. XML output (that is, a string starting with
The Extensible Markup Language, or simply XML, is a simple text-based format for representing structured information: documents, data, configuration, books, transactions, invoices, and much more. Similar to JSON, it is an older way of storing data. Earlier APIs used to return data in XML format ; however, JSON is nowadays the preferred choice. Let’s see how we can face the expecting value: line 1 column 1 (char 0) type error in this case.
Let’s break down what is happening here.
- For ease of example, suppose API returns an XML format data, as shown above.
- Now, when we try to load that response from API, we will get a type error.
Resolving JSONDecodeError: Expecting value: line 1 column 1 (char 0)
1. Solution for Non-JSON conforming quoting
To resolve the type error in this case, you need to ensure that the keys and values are enclosed within the double quotes. This is necessary because it is a part of JSON syntax. It is important to realize that JSON only uses double quotes, not single quotes.
2. Solution for empty JSON file
The solution for this is self-evident in the name. To resolve the type error, in this case, make sure that the JSON file or the response from an API is not empty. If the file is empty, add content to it, and for a response from an API, use try-except to handle the error, which can be empty JSON or a 404 error, for instance.
The above code takes in a word and returns all the information related to it in a JSON format. Now in order to show how we can handle the Expecting value: line 1 column 1 (char 0) type error, we have altered the URL. entries have been changed to enties. Therefore we will get an invalid response which will not be of the JSON format. However, this is merely done to imitate the error when you might get an invalid response from an API.
- Now, if you try to run the code above, you will be prompted to enter a word. The response is saved into the data variable and later converted to a string.
- However, in the try block json.loads method, which parses JSON string to python dictionary raises an error.
- This is because the response sent by API is not of JSON format, hence can’t be parsed, resulting in JSONDecodeError.
- JSONDecodeError gets handled by the try-except block, and a “Response content is not valid JSON” gets printed as an outcome.
3. Solution for XML output(that is, a string starting with
To avoid type errors resulting from an XML format, we will convert it to a JSON format. However, firstly install this library.
Let’s elaborate on the code above:
- We have imported two libraries, namely JSON and xmltodict.
- Using the context manager with, XML file test.xml is opened in read mode. Thereafter using the xmltodict parse method, it is converted to a dictionary type, and the file is closed.
- json.dumps() takes in a JSON object and returns a string of that object.
- Again using context manager with, a JSON file is created, XML data that was converted to a JSON string is written on it, and the file is closed.
JSONDecodeError: Expecting value: line 1 column 1 (char 0) Django
This issue is caused by the failure of Pipenv 2018.10.9. To resolve this issue, use Pipenv 2018.5.18. For more, read here.
Are you facing this error in Flask?
Many times, when you receive the data from HTTP requests, they are fetched as bytes. So, if you face JSONDecodeError, you might be dealing with a JSON in bytes. First, you need to decode the JSON by using response.decode(‘utf-8’) . This will create a string, and then you can parse it.
json.loads() method can be used to parse JSON in python. For instance:
import json
json_string = ‘<«a»:»1″, «b»:»2″, «c»:»3″>‘
json_to_dict = json.loads(json_string)
print(json_to_dict)
print(type(json_to_dict))
import os
file_path = «/home/nikhilomkar/Desktop/test.json»
print(«File is empty!» if os.stat(file_path).st_size == 0 else «File isn’t empty!» )
The following code checks if the file is empty and prints the File is empty! If true, else, the File isn’t empty!.
Conclusion JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The following article discussed the JSONDecodeError: Expecting value: line 1 column 1 (char 0). This error is due to various decoding and formatting errors. We looked at likely situations where it can occur and how to resolve it.
Источник
Python JSONDecodeError: Expecting value: line 1 column 1 (char 0)
If you try to parse invalid JSON or decode an empty string as JSON, you will encounter the JSONDecodeError: Expecting value: line 1 column 1 (char 0). This error can occur if you read an empty file using json.load, read an empty JSON or receive an empty response from an API call.
You can use a try-except code block to catch the error and then check the contents of the JSON string or file before retrying.
This tutorial will go through the error in detail and how to solve it with code examples.
Table of contents
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
In Python, JSONDecodeError occurs when there is an issue with the formatting of the JSON data. This specific error tells us the JSON decoder has encountered an empty JSON.
Example #1: Incorrect use of json.loads()
Let’s look at an example where we have a JSON file with the following contents:
We want to read the data into a program using the json library. Let’s look at the code:
In the above code, we try to read the data in using json.loads() . Let’s run the code to see the result:
The error occurs because json.loads() expects a JSON encoded string, not a filename. The string pizza.json is not a valid JSON encoded string.
Solution
We need to use json.load() instead of json.loads() to read a file. Let’s look at the revised code:
In the above code, we use the open() function to create a file object that json.load() can read and return the decoded data object. The with statement is a context manager that ensures that the file is closed once the code is complete. Let’s run the code to see the result:
Example #2: Empty JSON file
Let’s look at an example where we have an empty file, which we will try to read in using json.loads() . The file is called particles.json . Since the JSON file is empty, the JSON decoder will throw the JSONDecodeError when it tries to read the file’s contents. Let’s look at the code:
Solution
If the file is empty, it is good practice to add a try-except statement to catch the JSONDecodeError. Let’s look at the code:
Now we have verified the file is empty, we can add some content to the file. We will add three particle names together with their masses.
Let’s try to read the JSON file into our program and print the contents to the console:
We successfully read the contents of the file into a list object.
Example #3: Response Request
Let’s look at an example where we want to parse a JSON response using the requests library. We will send a RESTful GET call to a server, and in return, we get a response in JSON format. The requests library has a built-in JSON decoder, response.json(), which provides the payload data in the JSON serialized format.
We may encounter a response that has an error status code or is not content-type application/json . We must check that the response status code is 200 (OK) before performing the JSON parse. Let’s look at the code to check the response has the 200 status code and has the valid content type. application/json .
In the above example, we use httpbin.org to execute a GET call. Let’s run the code to get the result:
Summary
Congratulations on reading to the end of this tutorial! The JSONDecodeError: Expecting value: line 1 column 1 (char 0) occurs either when data is not present in a file, the JSON string is empty, or the payload from a RESTful call is empty.
You can resolve this error by checking the JSON file or string for valid content and using an if-statement when making a RESTful call to ensure the status code is 200 and the content type is application/json .
For further reading on errors involving JSON, go to the articles:
Источник
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Table of Contents Hide
If you are working with APIs and trying to fetch and parse the JSON data while making the HTTP or curl requests and JSON response is not well-formed, Python will throw json.decoder.jsondecodeerror: expecting value: line 1 column 1 (char 0).
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Let us take a look at the possible causes of JSONDecodeError and how we solve this issue in our code with some examples.
In most of cases, you get json.loads- JSONDecodeError: Expecting value: line 1 column 1 (char 0) error is due to :
- The response might be in some other format such as XML, HTML, etc.
- The JSON response is not structured properly.
- The response type doesn’t come in the format of application/json. Rather it comes in string format, which in turn throws a JSONDecodeError while parsing the response.
- Empty response
- Invalid status code or httpx error
Also, read the Python JSONPath tutorial
Example JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Let me demonstrate with a simple example of replicating a JSONDecodeError, and we will look at solving the same.
In this example, we are trying to load a JSON file from the specified path and print the contents of the JSON file. However, since the JSON file is empty, the JSON module will throw a JSONDecodeError when we try to read the empty content. It always expects the proper JSON structure.
Output
The json.loads(j.read()) tries to load the JSON content and parse the JSON, and during that time, if it’s not well structured, you get a JSONDecodeError.
Note: In this case, if the JSON file is not found, you will get a FileNotFoundError: [Errno 2] No such file or directory
Solution
The solution is simple and straightforward. Validate if the file is not empty and has proper JSON content. Now that we have added the proper content to the books.json file when we run the same code again, we get the below output.
Output
Other Possible Solutions
Ensure HTTP 200 status code and valid content type as application/json
If you are making requests to API, make sure to check the response status code is 200 (OK) and then perform JSON parse. Below is the sample snippet on how you can ensure to check the response has 200 status code and valid content type as application/json
Источник
JSONDecodeError: Expecting value: line 1 column 1 (char 0) occurs while working with JSON (JavaScript Object Notation) format. You might be storing some data or trying to fetch JSON data from an API(Application Programming Interface). In this guide, we will discuss where it can creep in and how to resolve it.
JSONDecodeError means there is an incorrect JSON format being followed. For instance, the JSON data may be missing a curly bracket, have a key that does not have a value, and data not enclosed within double-quotes or some other syntactic error.
Generally, the error expecting value: line 1 column 1 (char 0) error can occur due to the following reasons.
- Non-JSON conforming quoting
- Empty JSON file
- XML output (that is, a string starting with <)
Let’s elaborate on the points stated above:
1. Non-JSON conforming quoting
JSON or JavaScript Object Notation has a similar format to that of the python dictionary datatype. A dictionary requires a key or value to be enclosed in quotes if it is a string. Similarly, the JSON standard defines that keys need not be a string. However, keys should always be enclosed within double quotes. Not following this standard can also raise an error.
2. Empty JSON file
For this example, we have taken an empty JSON file named test.py and another file named test.py, which contains the code given below. Using context manager, we open the JSON file in reading mode and load it using the load method. However, an error is thrown because the JSON file is empty.
import json with open("test.json", "r") as file: data = json.load(file) print("Data retrieved")
3. XML output (that is, a string starting with <)
The Extensible Markup Language, or simply XML, is a simple text-based format for representing structured information: documents, data, configuration, books, transactions, invoices, and much more. Similar to JSON, it is an older way of storing data. Earlier APIs used to return data in XML format; however, JSON is nowadays the preferred choice. Let’s see how we can face the expecting value: line 1 column 1 (char 0) type error in this case.
<part number="1976"> <name>Windscreen Wiper</name> <description>The Windscreen wiper automatically removes rain from your windscreen, if it should happen to splash there. It has a rubber <ref part="1977">blade</ref> which can be ordered separately if you need to replace it. </description> </part>
import json with open("test.xml", "r") as file: data = json.load(file) print("Data retrieved")
Let’s break down what is happening here.
- For ease of example, suppose API returns an XML format data, as shown above.
- Now, when we try to load that response from API, we will get a type error.
Resolving JSONDecodeError: Expecting value: line 1 column 1 (char 0)
1. Solution for Non-JSON conforming quoting
To resolve the type error in this case, you need to ensure that the keys and values are enclosed within the double quotes. This is necessary because it is a part of JSON syntax. It is important to realize that JSON only uses double quotes, not single quotes.
2. Solution for empty JSON file
The solution for this is self-evident in the name. To resolve the type error, in this case, make sure that the JSON file or the response from an API is not empty. If the file is empty, add content to it, and for a response from an API, use try-except to handle the error, which can be empty JSON or a 404 error, for instance.
import json import requests def main(): URL = "https://api.dictionaryapi.dev/api/v2/enties/en/" word = input("Enter a word:") data = requests.get(url + word) data = data.text try: data_json = json.loads(data) print(data_json) except json.JSONDecodeError: print("Empty response") if __name__ == "__main__": main()
The above code takes in a word and returns all the information related to it in a JSON format. Now in order to show how we can handle the Expecting value: line 1 column 1 (char 0) type error, we have altered the URL. entries have been changed to enties. Therefore we will get an invalid response which will not be of the JSON format. However, this is merely done to imitate the error when you might get an invalid response from an API.
- Now, if you try to run the code above, you will be prompted to enter a word. The response is saved into the data variable and later converted to a string.
- However, in the try block json.loads method, which parses JSON string to python dictionary raises an error.
- This is because the response sent by API is not of JSON format, hence can’t be parsed, resulting in JSONDecodeError.
- JSONDecodeError gets handled by the try-except block, and a “Response content is not valid JSON” gets printed as an outcome.
3. Solution for XML output(that is, a string starting with <)
To avoid type errors resulting from an XML format, we will convert it to a JSON format. However, firstly install this library.
pip install xmltodict
import json import xmltodict with open("test.xml", "r") as file: data = xmltodict.parse(file.read()) file.close() json_data = json.dumps(data) with open("t.json", "w") as json_file: json_file.write(json_data) json_file.close() print("Data retrieved") print(data)
Let’s elaborate on the code above:
- We have imported two libraries, namely JSON and xmltodict.
- Using the context manager with, XML file test.xml is opened in read mode. Thereafter using the xmltodict parse method, it is converted to a dictionary type, and the file is closed.
- json.dumps() takes in a JSON object and returns a string of that object.
- Again using context manager with, a JSON file is created, XML data that was converted to a JSON string is written on it, and the file is closed.
JSONDecodeError: Expecting value: line 1 column 1 (char 0) Django
This issue is caused by the failure of Pipenv 2018.10.9. To resolve this issue, use Pipenv 2018.5.18. For more, read here.
Are you facing this error in Flask?
Many times, when you receive the data from HTTP requests, they are fetched as bytes. So, if you face JSONDecodeError, you might be dealing with a JSON in bytes. First, you need to decode the JSON by using response.decode('utf-8')
. This will create a string, and then you can parse it.
FAQs
How to parse JSON in python?
json.loads() method can be used to parse JSON in python. For instance:import json
json_string = '{"a":"1", "b":"2", "c":"3"}'
json_to_dict = json.loads(json_string)
print(json_to_dict)
print(type(json_to_dict))
How to detect empty file/string before parsing JSON?
import os
)
file_path = "/home/nikhilomkar/Desktop/test.json"
print("File is empty!" if os.stat(file_path).st_size == 0 else "File isn't empty!"
The following code checks if the file is empty and prints the File is empty! If true, else, the File isn’t empty!.
Conclusion JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The following article discussed the JSONDecodeError: Expecting value: line 1 column 1 (char 0). This error is due to various decoding and formatting errors. We looked at likely situations where it can occur and how to resolve it.
Trending Python Articles
-
“Other Commands Don’t Work After on_message” in Discord Bots
●February 5, 2023
-
Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials
by Rahul Kumar Yadav●February 5, 2023
-
[Resolved] NameError: Name _mysql is Not Defined
by Rahul Kumar Yadav●February 5, 2023
-
Best Ways to Implement Regex New Line in Python
by Rahul Kumar Yadav●February 5, 2023
Hi!
Please run
import requests
r = requests.get('http://httpbin.org/status/200')
r.status_code
r.json()
The answer is:
200
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I do not think it is informative and maybe it could contain something like:
Json: Response content is not in the json format
Do you think it is a good idea to wrap line 892 of requests/models.py into something like:
try:
return complexjson.loads(self.text, **kwargs) # current line 892
except JSONDecodeError:
print('Response content is not in the json format')
?
System Information
(py3) ~/ $ python -m requests.help
{
"chardet": {
"version": "3.0.4"
},
"cryptography": {
"version": ""
},
"idna": {
"version": "2.6"
},
"implementation": {
"name": "CPython",
"version": "3.6.6"
},
"platform": {
"release": "4.15.0-39-generic",
"system": "Linux"
},
"pyOpenSSL": {
"openssl_version": "",
"version": null
},
"requests": {
"version": "2.18.4"
},
"system_ssl": {
"version": "1010007f"
},
"urllib3": {
"version": "1.22"
},
"using_pyopenssl": false
}
The error “JSONDecodeError: Expecting value: line 1 column 1 (char 0)” can happen when you working with Python. Learn why Python raises this exception and how you can resolve it.
Reproduce The Error
Python provides a built-in module for encoding and decoding JSON contents, which can be strings or files. The loads()
is one of the most popular functions in this module. However, it raises a JSONDecodeError instead:
>>> import json
>>> json.loads(“”)
Traceback (most recent call last):
File “/usr/lib/python3.10/json/decoder.py”, line 355, in raw_decode
raise JSONDecodeError(“Expecting value”, s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
When you read an empty JSON file with load()
, Python will also print out a similar error message:
>>> import json
>>> with open("empty.json", "r") as emptyJSON:
... print(json.load(emptyJSON))
....
Traceback (most recent call last):
File "/usr/lib/python3.10/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 2)
You can run into this error outside the json module as well. Requests is a popular library for dealing with HTTP requests in Python. It supports the json()
method, which converts the fetched content from a resource URI into a JSON object. But it can unexpectedly raise the JSONDecodeError exception:
>>> import requests
>>> URL="http://httpbin.org/status/200"
>>> response = requests.delete(URL)
>>> print(response.json())
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
…
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Explain The Error
The first two examples are obvious. The error message is displayed in those cases because you provide load()
and loads()
with empty JSON content.
When those methods fail to deserialize and parse a valid JSON document from those sources, they raise the JSONDecodeError exception.
From this clue, we can guess why the response.json()
method in the third example also produces the same error.
There is a high chance the response object itself is empty. This is indeed true, which can be verified by using response.text
to get the content of the response:
This is a common response message when we send an HTTP DELETE request to delete a resource. This can be the case even with the status code 200 (meaning the deleting action has been carried out).
Solutions
Refraining from parsing empty files and strings as JSON documents is an obvious fix. But in many situations, we can’t control whether a data source can be empty or not.
Python, however, allows us to handle exceptions like JSONDecodeError. For instance, you can use the try-catch
statements below to prevent error messages in the case of empty strings and files:
Example 1
try: json.loads("") except json.decoder.JSONDecodeError: print("")
Example 2
try: with open("empty.json", "r") as emptyJSON: print(json.load(emptyJSON)) except json.decoder.JSONDecodeError: print("")
Those snippets execute the loads()
and load()
functions. If the JSONDecodeError exception is raised, Python executes the except
clause and prints an empty string instead of an error message.
We can apply the same idea when parsing the content of an HTTP request response:
try: URL = "http://httpbin.org/status/200" response = requests.delete(URL) print(response.json()) except requests.exceptions.JSONDecodeError: print("")
It is important to note that you must change the exception to catch from json.decoder.JSONDecodeError
to requests.exceptions.JSONDecodeError
.
Summary
Python throws the error “JSONDecodeError: Expecting value: line 1 column 1 (char 0)” when it parses an empty string or file as JSON. You can use a try
statement to catch
and handle this exception.
Maybe you are interested in similar errors:
- DataFrame constructor not properly called!
- ModuleNotFoundError: No module named ‘tensorflow’ in python
- ModuleNotFoundError: No module named ‘scipy’ in Python
- RuntimeError: dictionary changed size during iteration
My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.
Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: Java, C#, C, Javascript, R, Typescript, ReactJs, Laravel, SQL, Python
#django #django-rest-framework #django-views
Вопрос:
Я создал простой фреймворк Django REST, и я могу его ПОЛУЧИТЬ. Однако при попытке ОПУБЛИКОВАТЬ я получаю следующее:
"detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)"
Ниже я прикрепил свои модели, URL-адреса, представления и сериализаторы.
Мой Models.py
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
class Meta:
ordering = ['created']
serializers.py
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = '__all__'
#fields = ['id', 'title', 'code', 'linenos', 'language', 'style']
urls.py
urlpatterns = [
path('snippets/', views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail),
]
urlpatterns = format_suffix_patterns(urlpatterns)
Views.py
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.response import Response
@api_view(['GET','POST'])
@csrf_exempt
def snippet_list(request,format=None):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
elif request.method == 'POST':
print("the request",request.data)
data = JSONParser().parse(request)
serializer = SnippetSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
«это довольно простое приложение API » ПОЛУЧИТЬ,ПОМЕСТИТЬ,УДАЛИТЬ»».
@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, pk,format=None):
"""
Retrieve, update or delete a code snippet.
"""
try:
snippet = Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = SnippetSerializer(snippet)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = SnippetSerializer(snippet, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
Почему я могу ПОЛУЧИТЬ, но не ОПУБЛИКОВАТЬ?
Ответ №1:
Поскольку ваше представление на основе функций использует @api_view
декоратор, вам не нужно анализировать тело запроса, как это уже сделано для вас. Просто доступ request.data
:
elif request.method == 'POST':
serializer = SnippetSerializer(data=request.data)
Это то же самое, что и то, для чего у вас сейчас есть PUT
.