Json response ошибка

Were you trying to upload a file or edit a piece of content on your WordPress site only to be met by a scary red message saying something like, «Updating failed. The response is not a valid JSON response?»

Wordpress developer troubleshooting the invalid JSON response error

The WordPress invalid JSON response error happens in the new Block Editor (AKA Gutenberg) when something goes wrong on your site. Because it appears when you’re working on content, it can be a frustrating error because it can get in the way of whatever task you’re trying to accomplish.

Thankfully, there are some straightforward steps that you can take to fix this problem and get your site working properly again.

In this post, we’ll briefly explain what the invalid JSON response error means. Then, we’ll share a number of troubleshooting steps you can implement to fix the problem.Grow Your Business With HubSpot's Tools for WordPress Websites

If you see «Updating failed. The response is not a valid JSON response,» it will typically appear when you’re working on content in the WordPress Block Editor. In some cases, it can also appear when you’re trying to upload a media file to your site, especially if you’re trying to upload the file directly to a block in the Block Editor.

So, why does it happen?

When you’re working in the Block Editor, the editor is in constant communication with your WordPress site’s server. This «communication» happens behind the scenes, but it’s important to the editor.

One of the «languages» of this communication is JSON, short for JavaScript Object Notation. If something goes wrong with this communication, WordPress will show the «The response is not a valid JSON response» message. It means that the editor failed to get a response to the server or the response wasn’t in a valid JSON format.

Basically, if the editor can’t communicate with the server, it will show this error message instead.

To fix the problem, you essentially need to fix whatever is getting in the way of the communication.

How to Fix the WordPress Invalid JSON Response Error

Now that you know what the JSON response error message means, let’s dig into some troubleshooting steps to fix this problem.

We’ll try to put these in a logical order, so that the first troubleshooting steps are the most likely to fix the problem.

For that reason, we recommend trying these processes in the order that we’ve written them.

Fix your site’s permalinks and .htaccess file.

One of the most common causes of the invalid JSON response error is an issue with your site’s .htaccess file and/or WordPress permalinks.

Thankfully, this is also one of the simplest debugging steps. Here’s all you need to do:

  1. Go to Settings → Permalinks in your WordPress dashboard.
  2. Verify that the correct permalink structure is selected — If the correct structure is already selected, you don’t need to change anything.
  3. Click the Save Changes button. Even if you didn’t change anything, you should still click the save changes button because it will force WordPress to regenerate its rewrite rules.

WordPress JSON error fix

Now, go back to the editor and see if that fixed the invalid JSON response error.

If you’re still experiencing issues, you can guarantee that your .htaccess file is clean by deleting it and forcing WordPress to generate a new one. Here’s how:

  1. Connect to your server using an FTP client or cPanel File Manager.
  2. Find your .htaccess file (it should be in the root folder).
  3. Download a copy of the file to your computer as a backup (just in case).
  4. Delete the file from your server.
  5. Go to Settings → Permalinks in your WordPress dashboard and click Save Changes. This will force WordPress to generate a new, clean .htaccess file.
  6. Check if the problem is fixed.

Finally, there’s one last potential fix, but it really only applies to advanced WordPress users.

If you’re working in a local development environment via a tool such as XAMPP, you’ll also want to make sure that you’ve properly configured the .htaccess file permissions and enabled mod_rewrite in Apache’s settings. Make sure to restart Apache once you’ve made the changes.

Check your WordPress site URL.

Another common cause of the invalid JSON response error is a problem with your WordPress site URLs.

The problem can arise if your site URLs aren’t correct or if you accidentally put HTTP instead of HTTPS (assuming your site is using an SSL certificate).

To fix this problem, go to Settings → General in your WordPress dashboard.

You’ll want to verify two things here:

  1. Make sure that the URLs are correct. On the vast majority of WordPress sites, your WordPress Address and Site Address should be the same.
  2. Make sure that both URLs start with https if you’re using an SSL certificate on your site.

Then, save your changes.

WordPress JSON error resolution

In very rare cases, your site’s URLs might have been hard-coded into your wp-config.php file. If this is so, any changes that you make via your WordPress dashboard won’t apply because those hard-coded changes will override the dashboard settings.

Again, this is very rare because you need to manually add those hard-coded changes, but it can happen so it might be worth checking. For example, your WordPress developer might have done this for you without letting you know.

Here’s how to check if this is the case:

  1. Connect to your site’s server using FTP or cPanel File Manager.
  2. Edit the wp-config.php file.
  3. Search for define( ‘WP_HOME’ OR define( ‘WP_SITEURL’

Here’s an example of what it might look like:

JSON error example

If you do find these code snippets, you can either:

  1. Verify that both site URLs are correct and leave the code snippets in your wp-config.php file.
  2. Remove the code snippets, which will tell your site to use the URLs that you set in your WordPress dashboard.

Check for a mixed content warning (HTTPS issue).

If your site is using an SSL certificate (which most sites do nowadays), issues with mixed HTTP and HTTPS content can trigger the invalid JSON response error.

In order for your website to benefit from the security of your SSL certificate, you need to use HTTPS to load every resource on your site. If you still have some resources loading over HTTP, this can trigger something called a mixed content warning and which causes problems with the invalid JSON response error.

In the previous section, you made sure that your WordPress site URLs both start with HTTPS (if you’re using an SSL certificate), which should fix many problems with mixed content already.

However, there could still be issues, especially if you’re using a plugin to handle migrating an older site from HTTP to HTTPS.

If you’re using a plugin, make sure that you’ve fully enabled its mixed content fixer features. You can do this by going to Settings → SSL and enabling both the Mixed content fixer and the Fire mixed content fixer with different method toggles:

JSON error plugin fix

If you’re not using an SSL plugin, many hosts now offer tools to force HTTPS, which you can find in your hosting dashboard or by consulting your host’s documentation.

Finally, if you’re using Cloudflare on your site, make sure that you’ve set its Encryption Mode to Full (Strict) or Full. Try the Strict option first and then switch to just Full if you experience any issues.

Disable your security firewall.

If you use a firewall to protect your WordPress site, this can sometimes interfere with the editor’s connection to your server and trigger the invalid JSON response error.

This is especially common with ModSecurity rules from your web host, though it also might be triggered by popular security plugins.

To troubleshoot this, try deactivating your firewall or security plugin and see if that fixes the problem. If the editor starts working, you know that something is going wrong with your firewall.

Of course, leaving the firewall disabled isn’t a viable long-term strategy, but you at least now know what’s causing the problem and you can start fixing things.

If your firewall is implemented at the hosting level, you can ask your WordPress host to investigate and whitelist the editor to avoid having it trigger the firewall. That way, you can maintain the protection of your site’s firewall while still avoiding the invalid JSON response error.

If you’re using a WordPress security or firewall plugin, you have two options:

  1. You can replace your existing firewall plugin with a different plugin that protects your site without causing problems.
  2. You can reach out to the plugin’s developer to ask them about whitelisting to avoid future problems.

If you’re using Wordfence (or another plugin that has a «learning mode»), you can also try reactivating learning mode to reset its firewall rules.

Use a classic editor plugin.

Some people report being able to fix the invalid JSON response error by activating and deactivating the Classic Editor (WordPress’ old, TinyMCE-based editor).

It only takes a couple of minutes, so it’s worth seeing if this trick can fix your problems.

Here’s all you need to do:

  1. Install the official Classic Editor plugin from WordPress.org.
  2. Go to Settings → Writing and use the drop-down to select the Classic Editor as the default editor for all users.
  3. Save your changes.
  4. Use the same drop-down to change the default editor back to the Block Editor.
  5. Save your changes again.

Classic editor JSON error

Now, try creating or editing a new post and see if it works.

Deactivate your WordPress plugins.

Debugging WordPress errors can be tricky because the plugins that you’re using introduce a lot of variables to the equation. With 58,000+ plugins at WordPress.org, that’s a lot of edge cases that could be triggering the invalid JSON response error.

One easy way to figure out if a plugin is causing the problem is to deactivate all of your plugins.

If you’re still seeing the invalid JSON response error after deactivating everything, you can be confident that it’s not an issue with your plugins and you can reactivate them.

On the other hand, if the error goes away after deactivating your plugins, you know that there’s a problem with one of the plugins that you’re using.

To find the problematic plugin, you can reactivate your plugins one by one, making sure to test the editor after each plugin. If you activate a plugin and see the error appear right after that, you’ve found the issue.

From there, you can either replace that plugin with an alternative that doesn’t cause a problem or you can reach out to the plugin’s developer for help and a potential fix.

Upload media files via the Media Library.

If you’re seeing the «The response is not a valid JSON response» when you try to upload media files via the Block Editor, one fix is to upload these images directly to your Media Library instead of via the block interface.

When you add an image block (or the block for another type of media file), click on the Media Library option and upload files that way instead of just clicking the Upload button.

When you do that, you’ll see the regular WordPress Media Library uploader interface, which should let you bypass the invalid JSON response error.

JSON error wordpress

Check the console and debug log.

For more advanced users, you can try digging into your browser’s console or various debug logs to find a more specific problem. This isn’t really a solution for casual users, though, as you’ll need some technical knowledge to accomplish anything here.

First off, you can use the Network tab in Chrome Developer Tools to find issues with Ajax calls.

In the Network tool, select FETCH/XHR to filter out Ajax calls and debug issues with the REST API.

JSON error Debug log

You can also view some REST API issues from your WordPress dashboard. Go to Tools → Site Health and look for a heading such as «The REST API encountered an unexpected result».

Use the Classic Editor as a short-term fix.

This last method isn’t a permanent fix, but it is a workaround that can help you publish content in a pinch.

Earlier, we told you about the Classic Editor trick where you switch your site to the Classic Editor but then switch back to the Block Editor.

Well, if none of the other tips have worked for you, one way to continue publishing content is to just leave the Classic Editor enabled and use that to create content for the time being.

This isn’t an actual «fix» because you’ll lose all of the functionality that the Block Editor adds. However, it will give you the ability to work on content while you continue debugging the «The response is not a valid JSON response» message.

Additionally, once you get the Block Editor working again, you’ll be able to convert your Classic Editor content into blocks with just a few clicks.

Fixing the WordPress Invalid JSON Response Error

Seeing a «Updating failed. The response is not a valid JSON response» message can be frustrating because it appears while you’re trying to work in the WordPress editor.

Thankfully, for most sites, debugging this error shouldn’t be too painful.

In most situations, simply re-saving your WordPress permalinks should fix the problem. If that doesn’t work, you might need to dig into other fixes such as checking your site URLs, fixing mixed content warnings with HTTPS, adjusting your firewall, and more. Implement these troubleshooting steps and you should have your site functioning properly again in no time.Use HubSpot tools on your WordPress website and connect the two platforms  without dealing with code. Click here to learn more.

Since the Gutenberg WordPress editor became the default page editor, many WordPress users have started seeing “The response is not a valid JSON response” error messages on their website trying to update posts or upload media. While switching back to the classic editor immediately solves the issue and might be a great temporary fix, WordPress invalid JSON errors indicate an issue with REST API, which WordPress absolutely relies on to work correctly.

In this guide, you will learn how the Gutenberg editor works with REST API and how to fix “The response is not a valid JSON response” message in WordPress in a comprehensive, step-by-step manner.

How Does Gutenberg Work With REST API and JSON?

The Gutenberg WordPress editor, also known as the block editor, is a front-end application that uses REST API to communicate data between the server and user interface. Making it the default option built into WordPress core, WordPress fully replaced the classic editor with Gutenberg, taking a huge step towards full site editing.

The Gutenberg WordPress editor is a client-side application which means that it runs in the user’s browser and does not have direct access to the WordPress database, where all posts and pages are stored. Therefore, the block editor needs a way to communicate with the server to send content updates. REST API is what ensures client-server communication and allows Gutenberg to update posts and pages by sending and receiving data as JSON objects.

JSON stands for JavaScript Object Notation and is used by WordPress to create a representation of content in the schema defined by the WordPress REST API. Anytime you are editing a page or a post using Gutenberg and click on the Update button to have all changes you made saved, the block editor sends a request to the server and expects a response in JSON format.

the response is not a valid JSON response

What Does “The response is not a valid JSON response” Error Mean?

When the client-server communication is interrupted, or Gutenberg fails to reach the server, WordPress will recognize the message received back as an invalid JSON response and show “The response is not a valid JSON response.”

The WordPress invalid JSON response error can appear on your website when you are trying to update or publish a post from the block editor or upload media. By showing an error message, WordPress informs you that the task you wanted to perform failed. As a result, the update you made will not be saved to the server until normal client-server communication is restored.

"the response is not a valid JSON response” Message in WordPress

Top 5 Issues Behind “The response is not a valid JSON response” Error and How to Address Them

There are 5 main issues behind “The response is not a valid JSON response” error message in WordPress:

  1. Incorrect WordPress site address setting
  2. Broken permalinks
  3. SSL errors and competing redirects
  4. Security solutions blocking requests
  5. Plugin conflicts

Incorrect WordPress Site Address Settings

Wrongly configured WordPress Address and Site Address settings will interrupt the correct work of REST API, leading to “The response is not a valid JSON response” message on your WordPress website. Having both settings incorrect can be often seen after website migration or cloning when the URLs have not been updated to reflect the new domain name.

The WP_HOME and WP_SITEURL constants are used by WordPress to identify the address of your website. The WordPress Address setting refers to the location of the WordPress installation, while Site Address represents the URL your visitors need to type in the browser address bar to open your site.

Most of the time, both WP_HOME and WP_SITEURL constant have the same value and are auto loaded from the wp_options table of your WordPress database, where they are stored as the siteurl and home options. Siteurl and home can be found in the first two rows of wp_options. As both settings represent a Uniform Resource Locator, the correct protocol needs to be included.

SiteURL

WordPress Address and Site Address can also be used to force HTTPS on your website, which is often missed when trying to investigate competing redirects. An incorrect protocol specified in siteurl and home can lead to many issues, including the “Too many redirects” error.

How to Address

There are multiple ways to set your WordPress Address and Site Address settings, including modifying your wp-config.php file and WP CLI. But the easiest way to do it is by using the WordPress admin interface.

Open the General Settings menu from your WordPress dashboard and check the WordPress Address and the Site Address settings. Make sure they have the correct website address and protocol used. If you have a valid SSL certificate installed on the server, use HTTPS to ensure secure connections. Correct the values if needed and click on the Save Changes button.

WordPress General Settings

Broken Permalinks

WordPress permalinks are the unique URLs configured for all posts and pages on the website. Broken permalinks will not allow you to save any updates to posts and pages from the block editor, and will lead to seeing “The response is not a valid JSON response” on your website. Moreover, you will see the “404 Page Not Found” error message on all website pages, so no content will be available until you fix the permalink structure.

The requested URL was not found on this server

How to Address

Browse your website to see if all posts and pages load correctly. If you are receiving the “Not Found” error messages, examine the .htaccess file in your WordPress website’s document root directory to make sure the default redirect rules are there.

If the default code is missing, add it manually and save the file. Alternatively, you can resave your permalink structure from the WordPress admin area by navigating to Settings > Permalinks and clicking on the Save Changes button.

rewriteengine

SSL Errors and Competing Redirects

Competing redirects, mixed content errors, or other SSL issues can be the reason behind seeing “The response is not a valid JSON response” WordPress error or the “ERR_TOO_MANY_REDIRECTS” message on your website. Let’s review each situation to understand how it affects the functionality of your WordPress website.

SSL Errors and Mixed Content

If your SSL certificate has expired or has not been installed correctly, you will not be able to use HTTPS. If your WordPress website is configured to use secure connections and there are redirects in place to force HTTPS, it will lead to issues.

Mixed content is one of the most common issues with SSL which can be defined as a situation when the base HTML file is loaded via HTTPS, but other resources, including images, Javascript or CSS files, are delivered to the visitor via an insecure connection. In case mixed content is present, your browser will show the connection as not fully secure. Having content served over HTTP that is included in an HTTPS web page can lead to seeing WordPress invalid JSON response errors when working in the block editor.

Competing or Incorrect Redirects

Competing or incorrect redirects can cause a redirect loop on your WordPress website or break client-server communication when using the block editor, leading to “The response is not a valid JSON response” WordPress error. Having competing redirects means that there are at least two redirects, one trying to force HTTPS and the other redirecting back to HTTP.

One of the most common issues you can encounter is having a conflict between the redirects configured on the origin server and the ones applied by the content delivery network used. For example, CloudFlare offers three encryption modes — off, flexible, and full. Choosing the mode, you choose how CDN will request content from your server and deliver it to your website visitors.

A typical situation that causes issues, including “The response is not a valid JSON response” message in WordPress is having HTTPS forced on the server level when you have Cloudflare edge SSL installed, which only allows for encryption between the browser and Cloudflare. In that case, redirects forcing HTTPS configured on the origin server will create issues.

How to Address

The best way to avoid any SSL errors and competing redirects is to have a valid SSL installed, and ensure end-to-end encryption when using a content delivery network. Remember that you will need two certificates installed — one on your origin server and the other provided by the CDN.

SSL/TLS

Check if your WordPress website has a valid SSL certificate, and install a new one if the previous one has expired. In case your website shows as not fully secure even having a valid SSL certificate installed, mixed content is the most likely cause of seeing “The response is not a valid JSON response” message in WordPress. You can fix mixed content warnings by performing a search-replace on the WordPress database using WP CLI to remove any leftover HTTP references or use a plugin like Really Simple SSL that will do it for you.

You can also temporarily pause your CDN to see where exactly the connection fails. If you do not experience any issues saving post updates in Gutenberg having the CDN disabled, an issue exists in the way CDN communicates with the origin server, or the requests might be blocked by the web application firewall used in combination with your content delivery network.

Security Solutions Blocking WordPress’ Requests

Security solutions used, including WordPress security plugins, web application firewall rules implemented by content delivery network, or server-side WAFs like ModSecurity, can interrupt the correct client-server communication, leading to “The response is not a valid JSON response” message in WordPress.

Each security solution working on the application level presents a set of rules that each request sent to your WordPress websites is checked against in order to minimize the number of malicious requests coming to the web server. Once a certain rule is triggered, the request is blocked and an error message is returned, causing WordPress invalid JSON response errors shown.

How to Address

The best way to track down the issue is to check server and WAF logs to see if the request was actually blocked, and one of the security solutions is what caused the “The response is not a valid JSON response” error message to be shown. If you can not do it, deactivate your WordPress security plugin and any other solutions like Cloudflare WAF to see if it addresses the issue.

If it does, reach out to the plugin support team to help identify the rule-causing issues, or examine the list of rules yourself if there is an option for it. If you are still unable to save any updates from the block editor or upload media, a server-side security solution might be at fault. Your web hosting support team can help you address the issue by whitelisting the rule triggered for your IP address, or the website URL.

Make sure you are using a great WordPress security plugin that has managed rulesets that provide great protection against malicious requests, but at the same time do not interrupt you from performing website administration tasks. iThemes Security Pro actively monitors suspicious activity and helps you secure the most vulnerable parts of your WordPress website. Having the Site Scan feature enabled, you can be sure — no malware will go unnoticed.

Plugin Conflicts

When it comes to WordPress, plugin conflicts are one of the most common reasons why errors occur, including issues with REST API and having the “The response is not a valid JSON response” shown when trying to update posts and pages or upload data. The more plugins are activated at once, the higher the chance of code incompatibility, which in most cases won’t remain unnoticed.

How to Address

Deactivate all plugins to see if it solves the problem. If you no longer see the “The response is not a valid JSON response” error message, and all post updates made from the block editor are saved correctly, reactivate plugins one by one to identify the one causing issues.

You may notice that a certain plugin has recently been updated, so you may need to roll back the update to go back to the version that worked correctly. Check the plugin users’ support requests to see if others experienced the same issue. It is possible that the problem will be addressed in the next release or there is a known fix that will allow you to keep using the plugin.

iThemes Security Version Management allows you to auto-update WordPress, plugins, and themes to leverage new features, stay protected from known vulnerabilities, and avoid any interruptions to the correct work of your WordPress website.

Update Plugins

With various issues that can cause the “The response is not a valid JSON response” error message to appear on your WordPress website, it can be difficult to troubleshoot it and understand where to start. Do not rush into applying all fixes outlined in this guide. Follow the steps below to fix WordPress invalid JSON response errors once and for all.

Step 1. Identify Any Recent Changes

Start with doing a basic check of your website. See when the last WordPress core and plugin updates were performed and think whether anything might have changed on your website since the last time you were able to save content updates from the block editor and upload media to your website.

You may realize that a plugin has been recently updated, a new set of rules was added to your web application firewall, or you had to restore your website from a backup because it had been hacked. Knowing what exactly happened that caused the “The response is not a valid JSON response” error message will greatly help you understand where to start and save you time and effort.

Step 2. Examine Your WordPress Website

To fix the “The response is not a valid JSON response” error message in WordPress, the scope of search needs to be limited. Most of the issues described in the previous section of this article will cause more serious issues than just an inability to save content updates in Gutenberg or upload media.

Browse your website pages

Browse your website to see if you can load all web pages, and your browser shows the connection as fully secure on all of them. As a result, you can easily determine if there are any issues with SSL, your permalink structure, or redirects. Broken permalinks will result in the “Not Found” error messages shown on web pages, conflicting redirects may lead to seeing “ERR_TOO_MANY_REDIRECTS”.

Check your WordPress address settings and SSL

Check your WordPress address settings, including the protocol used in the URLs, and make sure your SSL certificate is valid and is trusted by all browsers by using an SSL checker. If you are using a CDN, check your encryption settings and make sure the redirects you set up on the server do not conflict with what your content delivery network enforces.

Step 3. Fix “The Response is not a valid JSON response” Message in WordPress

If you have carefully examined your WordPress website and noted all updates that have been recently made to it, you will be able to determine what has caused the “The response is not a valid JSON response” error message to appear when using the block editor or uploading media.

Unless your permalink structure is broken or there are any other serious issues that cause other errors on your website, you can temporarily switch to the classic editor if you absolutely need to publish a certain post as soon as possible. Install the Classic Editor plugin, which will replace the block editor upon activation. Once a post is published, you can resume the troubleshooting process.

Follow the instructions included in the previous section of this guide to address the issue you have identified. If your WordPress site address settings are correct, permalinks are working as expected, and you have ruled out all issues with SSL, mixed content, and competing redirects, deactivate your security solutions. If it doesn’t help, deactivate all plugins to see if a plugin conflict is at fault.

If nothing helped to identify the issue and you are unsure what is causing the “The response is not a valid JSON response” error message on your website, contact your web hosting support team for assistance. You may need a second pair of eyes which is completely normal. Moreover, support administrators will be able to check server logs which can speed up the troubleshooting process.

Conclusion

The WordPress block editor is a client-side application that uses REST API to communicate with the server and send data. Any interruption to the client-server communication will result in errors, including “The response is not a valid JSON response.” WordPress invalid JSON response errors can be caused by different issues, the most common of which are incorrect WordPress address settings, broken permalink structure, SSL errors, and conflicting redirects.

Sometimes, a WordPress site can be blocked by a security plugin or another solution used as a web application firewall. The best way to minimize the possibility of having requests sent from the admin dashboard blocked and save time troubleshooting errors while being fully protected from malicious traffic is by choosing the right security software.

There is a fine line between security and usability, but you do not need to choose between those. iThemes Security Pro is a WordPress security plugin that allows you to focus on daily tasks and be sure that your WordPress website is protected from all known vulnerabilities and security threats.

Get the bonus content: A Guide to WordPress Security

Kiki Sheldon

Kiki has a bachelor’s degree in information systems management and more than two years of experience in Linux and WordPress. She currently works as a security specialist for Liquid Web and Nexcess. Before that, Kiki was part of the Liquid Web Managed Hosting support team where she helped hundreds of WordPress website owners and learned what technical issues they often encounter. Her passion for writing allows her to share her knowledge and experience to help people. Apart from tech, Kiki enjoys learning about space and listening to true crime podcasts.

json response which is working correctly :

obj = urllib.urlopen("http://www.omdbapi.com/?t=Fight Club")
response_str = obj.read()
response_json = simplejson.loads(response_str)

above code making the json request which looks like :

{
    "Title":"Fight Club",
    "Year":"1999",
    "Rated":"R",
    "Released":"15 Oct 1999",
     ......
    "Response":"True"
}

so i can sleep now… but

json response which is not working correctly :

obj = urllib.urlopen("https://api.stackexchange.com/2.1/answers?order=desc&sort=activity&site=stackoverflow")
response_str = obj.read()
response_json = simplejson.loads(response_str)

above code making the json request which looks like :

{

    "items": [
        {
            "question_id": 18384375,
            "answer_id": 18388044,
            "creation_date": 1377195687,
            "last_activity_date": 1377195687,
            "score": 0,
            "is_accepted": false,
            "owner": {
                "user_id": 1745001,
                "display_name": "Ed Morton",
                "reputation": 10453,
                "user_type": "registered",
                "profile_image": "https://www.gravatar.com/avatar/99a3ebae89496eb16afe453aae97f5be?s=128&d=identicon&r=PG",
                "link": "https://stackoverflow.com/users/1745001/ed-morton"
            }
        },
        {
            "question_id": 18387447,
            "answer_id": 18388040,
            "creation_date": 1377195667,
            "last_activity_date": 1377195667,
            "score": 0,
            "is_accepted": false,
            "owner": {
                "user_id": 2494429,
                "display_name": "kpark91",
                "reputation": 140,
                "user_type": "registered",
                "profile_image": "https://www.gravatar.com/avatar/d903a03e7c5b6d9b21ff598c632de575?s=128&d=identicon&r=PG",
                "link": "https://stackoverflow.com/users/2494429/kpark91"
            }
        }

       ]
}

returns

JSONDecodeError at /
No JSON object could be decoded: line 1 column 0 (char 0)

instead of using simplejson i tried json which gave following error :

ValueError at /
No JSON object could be decoded

what i tried and failed:

I tried my questions’s answers on stackoverflow having same problem but none of them gave clear cut solution although every one helped me in some way

1) i checked whether json content encoding is correct or not

>>obj.info()

Content-Type: application/json; 
charset=utf-8
Content-Length: 2398

2) i decoded the response_str in utf-8

json.loads(response_str).decode("utf-8")

3) i used jsonlint to check format of json response

Parse error on line 1:

^
Expecting '{', '['

surprisingly following link of rescued my sleep.
JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Basically i was using exact code to get json response in both cases , but whats wrong with the second json response, only difference i noticed that the structure of second json response was different from first one.

please provide explanation to understand the issue.

Are you stuck to this “typeerror: res.json is not a function” error message while doing your program?

And so, continue reading to fix this error.

In this article, we’ll hand you the solutions for “res.json is not a function.” 

But before that, we’ll give you first a better understanding of this error.

The “typeerror: res.json is not a function” is an error message that can occur when working with Node.js applications and Express.

This error message indicates that the res.json() method, used to send JSON responses to clients, is not recognized as a function by the application.

For example:

const express = require('express');
const app = express();

app.get('/json', (res, req) => {
  res.json({ "message": "Hello json" });
});

app.listen(3000);

As you can see in our example, the arguments in the callback function are in the wrong order.

The first argument should be req (request), and the second should be res (response).

As a result, it will throw a “typeerror: res.json is not a function” error message.

Why does this error occur?

This error can occur for several reasons, such as:

❌ Overwriting the res variable in the code.

❌ Having the arguments in the handler method in the wrong order.

❌ Including version mismatches between dependencies.

❌ Missing middleware configuration

❌ Incorrect function calls

❌ Outdated Node.js versions.

How to fix “typeerror: res.json is not a function”?

Now that you fully understand why this error occurs in your code.
Let’s jump into the solutions to resolve this error.

Solution 1: Check the order of the arguments in the callback function

Ensure that the first argument is req (request) and the second is res (response).

For example:

app.get('/json', (res, req) => {
  res.json({ "message": "Hello json" });
});

To fix this error, you have to switch the order of the arguments.

const express = require('express');
const app = express();

app.get('/json', (req, res) => {
  res.json({ "message": "Hello json" });
});

app.listen(3000);

Solution 2: Avoid overwriting the res variable

Ensure that you are not overwriting the res variable in a callback function.

For example:

app.post('/danger', function response(req, res) {
  let placeId = req.body.data;
  let option = {
    uri: 'https://maps.googleapis.com/maps/api/directions/json?',
    qs: {
      origin: `place_id:${placeId[0]}`,
      destination: `place_id:${placeId[1]}`,
      language: 'en',
      mode: 'running',
      alternatives: true,
      key: APIKey
    }
  };
  rp(option)
    .then(function (response) { //change the variable name of "res" to "response"
      let dangerRate = dangerTest(JSON.parse(response), riskGrid);
      res.json({ data: [response, dangerRate] });
    })
    .catch(function (err) {
      console.error("Failed to get JSON from Google API", err);
    })
});

Solution 3: Ensure that you have included the required dependencies

Ensure that you have included all the required dependencies such as Express

For example:


const express = require('express');
const app = express();

Solution 4: Verify if you are using a library that makes .json a function

Unless you are using a library that makes .json a function, JavaScript uses JSON with two methods .parse() and .stringify().

When you are trying to set an object property by the name of .json.

res.json = { data: [res, dangerRate] };

Solution 5: Verify if you are using the new httpClient library

With the new httpClient library, you don’t have to call the .json() method.
You can use this simple map instead of the json method:

.map(res => res);

Difference between “res.json is not a function” and “responce.json is not a function”?

Both res.json is not a function and responce.json is not a function are error messages that may occur in the context of web development.

If you are confused about either of these two is the same, well the answer is “No.”

Response.json and res.json are not the same.

Response.json res.json
response.json is a method on the Response object in the Fetch API that reads the response and returns a promise that resolves with the result of parsing the body text as JSON. Res.json is a method on the res object in Express.js that sends a JSON response.

Both indicate that the json method is not recognized as a function of the response or res object, respectively.

The difference between the two error messages is the name of the variable used to reference the response object.

Conclusion

The “typeerror: res.json is not a function” is an error message that can occur when working with Node.js applications and Express.

This article already provides several solutions above so that you can fix the error message immediately.

We are hoping that this article provided you with sufficient solutions to get rid of the error.

You could also check out other “typeerror” articles that may help you in the future if you encounter them.

  • Typeerror: unhashable type: ‘dataframe’
  • Typeerror: ‘classmethod’ object is not callable
  • Typeerror: failed to construct ‘url’: invalid url

Are you trying to fix the invalid JSON error in WordPress?

This error appears when editing WordPress posts or pages on your website. You will see a message saying, ‘The response is not a valid JSON response’, and updating that page will fail.

In this article, we will show you how to easily fix the invalid JSON error in WordPress. We will also talk about why this error occurs and how to avoid it in the future.

JSON response is not valid error in WordPress

What Causes the ‘Not a Valid JSON Response’ Error in WordPress?

Failure to receive an expected response from the server causes the ‘Not a valid JSON response’ error in WordPress.

Basically, WordPress needs to communicate with the server while you are editing a blog post. It relies on getting responses from the web hosting server in the background. This response is usually in JSON format, which is used to quickly transport data using JavaScript.

If, for some reason, WordPress fails to get the response, or the response is not in JSON format, then you will see the ‘Not a valid JSON response’ error.

Not valid JSON response error displayed in WordPress

This error could appear for a number of reasons. However, the most likely cause of it is incorrect URL settings in WordPress or broken permalinks.

That being said, let’s take a look at how to easily fix the invalid JSON error in WordPress.

Important: Please make a complete WordPress backup before making any big changes to your website. This allows you to easily restore your website to its previous state.

1. Check WordPress URLs in Settings

First, you need to make sure that your WordPress Address and Site Address settings are correct.

Simply go to Settings » General page. From here, you need to review the ‘WordPress Address (URL)’ and ‘Site Address (URL)’ fields.

WordPress URL settings

For most websites, this setting must have the same URL in both fields.

However, rarely, some users may have given WordPress its own directory and serve the website on a different address. In that case, they can have different URLs here.

However, if your Site Address is incorrect, then that will trigger the invalid JSON error in WordPress.

If you made any changes to the settings, then don’t forget to click on the ‘Save Changes’ button. You can now edit a blog post and see if adding any new blocks or saving that post triggers the ‘Not valid JSON response’ error.

If you are still seeing the error, then continue reading.

2. Fix WordPress Permalink Structure

WordPress comes with SEO friendly URL structure that allows you to use human-readable URLs for your posts and pages.

However, sometimes a user may mess up the permalink settings. This would make it impossible for the WordPress editor to get a valid JSON response and cause the error to appear.

To fix this, you need to simply visit the Settings » Permalinks page. From here, you must carefully review the permalink options.

Fix permalinks in WordPress

If you are unsure whether you are using the right settings, then simply select one of the default formats.

After that, go ahead and click on the ‘Save Changes’ button to store your settings.

You can now try editing a blog post or page to see if the error has disappeared. If it hasn’t, then you can try this next step.

3. Regenerate WordPress .htaccess File

The .htaccess file in WordPress is used as a configuration file to manage SEO-friendly URLs (permalinks).

Normally, WordPress can automatically regenerate and update the file. You can also trigger that update by simply clicking on the ‘Save Changes’ button at the bottom of Settings » Permalinks page.

However, sometimes it may not get updated or has incorrect settings. This will affect your WordPress permalinks and may also cause an invalid JSON response error.

To fix this, you will need to connect to your website using an FTP client or the file manager app in your WordPress hosting account dashboard.

Once connected, you need to locate the .htaccess file in the root folder of your website and download it as a backup to your computer.

Download .htaccess file as a backup

Tip: Can’t locate the .htaccess file? See this quick article on how to find .htaccess file.

After that, you need to edit the .htaccess file using an FTP client or the file manager app.

Edit .htaccess file

Once the file opens, you need to delete all the code inside it and replace it with the following code:

# BEGIN WordPress

RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress

Don’t forget to save your changes and upload the file back to your website.

You can now visit your website and edit and post or page to see if you can reproduce the invalid JSON response error.

If you are still seeing the error, then there are a few more steps you can take.

4. View the REST API Debug Log

The invalid JSON response error can also mean that WordPress REST API on your website encountered an error.

The REST API is the set of techniques WordPress uses to communicate with the server as you work on your website.

You can see details of this error in the WordPress Site Health tool. Visit the Tools » Site Health page.

REST API issue in WordPress

From here, you may see an issue labeled ‘The REST API encountered an unexpected result’.

Clicking on it will show you more details, which may give you some clues about which plugin or third-party service is causing the issue.

If this doesn’t provide any clues, then you can move on to the next step.

5. Deactivate All WordPress Plugins

Occasionally, WordPress plugins may conflict with each other or the WordPress core software. This can result in unexpected behavior and could be a potential reason for the invalid JSON error.

Simply go to the Plugins » Installed Plugins page. From here, select all your WordPress plugins and then choose ‘Deactivate’ from the ‘Bulk Actions’ drop-down menu. Now, click the ‘Apply’ button to continue.

Deactivate all plugins

WordPress will now deactivate all your installed plugins.

You can now try again to reproduce the error. If the error disappears, then this means one of the plugins installed on your website was causing it.

To figure out which plugin is the problem, you just need to activate them one by one and try to reproduce the error. Repeat this until you find the culprit.

After that, you can reach out to the plugin author for support or find an alternative plugin.

6. Temporarily Switch to the Classic Editor

If all the above steps fail, then you can temporarily switch to the Classic Editor for WordPress.

This older version of the WordPress editor uses a simpler text editor and doesn’t rely heavily on REST API to get JSON responses.

To use it, you need to install and activate the Classic Editor plugin. For more details, see our step-by-step guide on how to install a WordPress plugin.

The plugin works out of the box, and it will disable the Gutenberg editor upon activation.

You can now continue working on your website and get back to troubleshooting later.

7. Further Troubleshooting

A number of things can block WordPress REST API or make it return an invalid JSON response. We have addressed the most likely culprits above, but if that didn’t fix it for you, then here are some more steps that you can try.

Switching to a Default WordPress Theme

Sometimes a conflict between your WordPress theme and a plugin or the WordPress core may result in unexpected behavior.

You can test this, by simply switching to a default WordPress theme like TwentyTwentyOne or Twenty-TwentyTwo.

Temporarily Turn Off Website Application Firewall

If you are using a WordPress firewall like Sucuri, Cloudflare, or a plugin, then it may sometimes block legitimate requests too.

The easiest way to figure this out is by temporarily disabling your WordPress firewall plugin or service.

Some application-level WordPress firewalls can be disabled by simply deactivating the plugin. For DNS-level firewalls like Sucuri and Cloudflare, you can disable them from your account dashboard.

Turn On Debugging in WordPress

WordPress comes with a built-in feature that allows you to keep a log of errors. However, it is not enabled by default.

To turn it on, you need to add the following code to your wp-config.php file:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );

After that, WordPress will keep a log of all errors in a debug.log file located inside the /wp-content/ folder. You can access this file by using an FTP client.

The error log may provide you with a clue about what may be causing the invalid JSON error on your website. For more details, see our guide on setting up WordPress error logs and using them for debugging errors.

Seek Expert Help

Finally, if all else fails, then this could be due to a misconfiguration on your WordPress hosting server. Most reliable WordPress hosting companies are able to help users with common WordPress issues.

Simply reach out to them via live chat or support ticket, and they may be able to help you fix it.

We hope this article helped you learn how to fix the invalid JSON error in WordPress. You may also want to see our complete handbook of the most common WordPress errors and how to fix them, along with our top picks for the best email marketing services for small business.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here’s our editorial process.

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Понравилась статья? Поделить с друзьями:
  • Jeep ошибка p0406
  • Jraid sys ошибка
  • Jeep ошибка p0401
  • Jeep grand cherokee ошибка p0101
  • Json parse обработка ошибок