Import json python ошибка

please use the stable python 2.7.x that would solve your issue and after that try using json

>>> import json

also you can use dir() command to check the methods and classes that comes with the json module in python programming, using the dir()

>>> dir(json)
['JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', '_default_decoder', '_default_encoder', 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads', 'scanner']

If you are a Python developer, you might have encountered the error message “NameError: name ‘json’ is not defined” at some point in your coding journey. This error occurs when you try to use the json module in your code, but Python cannot find it.

how to fix nameerror name json is not defined in python

In this tutorial, we will discuss the common causes of this error and how to fix it.

Why does the NameError: name 'json' is not defined error occur?

This error occurs when you try to use the json module in your Python code, but Python cannot find the json module in its namespace. The following are some of the scenarios in which this error usually occurs.

  1. You have not imported the json module.
  2. You have imported the json module using a different name.

The json module in Python is a built-in module that allows you to encode and decode JSON (JavaScript Object Notation) data. JSON is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. The json module provides the following two useful methods: json.dumps() to encode Python objects into a JSON formatted string, and json.loads() to decode a JSON formatted string into a Python object.

Since this module is part of the Python Standard Library, you don’t need to separately install it. You can simply import it and start using it.

Let’s now look at the above scenarios that may result in the above error in detail.

The json module is not imported

It can happen that you are trying to use the json module without even importing it. This is because Python does not recognize the json library and its functions until it is imported into the code.

For example, let’s try to use the json module without importing it and see what we get.

# note that the json module is not imported

# create a dictionary
person = {
    "name": "Kundan",
    "age": 26,
    "city": "Varanasi"
}

# convert dictionary to JSON string
person_json = json.dumps(person)

# print JSON string
print(person_json)

Output:

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

Cell In[1], line 11
      4 person = {
      5     "name": "Kundan",
      6     "age": 26,
      7     "city": "Varanasi"
      8 }
     10 # convert dictionary to JSON string
---> 11 person_json = json.dumps(person)
     13 # print JSON string
     14 print(person_json)

NameError: name 'json' is not defined

We get a NameError stating that the name json is not defined. To use the json library, you need to import it first.

import json

# create a dictionary
person = {
    "name": "Kundan",
    "age": 26,
    "city": "Varanasi"
}

# convert dictionary to JSON string
person_json = json.dumps(person)

# display JSON string
person_json

Output:

'{"name": "Kundan", "age": 26, "city": "Varanasi"}'

Here, we are importing the json module first and then using it to convert a Python dictionary object into a json string. You can see that we did not get any errors here.

The json module is imported using a different name

If you import the json module using a different name, for example import json as jsn, and then try to use the name “json” to use it, you will get a NameError because the name “json” is not defined in your current namespace.

Let’s look at an example.

import json as jsn

# create a dictionary
person = {
    "name": "Kundan",
    "age": 26,
    "city": "Varanasi"
}

# convert dictionary to JSON string
person_json = json.dumps(person)

# display JSON string
person_json

Output:

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

Cell In[1], line 11
      4 person = {
      5     "name": "Kundan",
      6     "age": 26,
      7     "city": "Varanasi"
      8 }
     10 # convert dictionary to JSON string
---> 11 person_json = json.dumps(person)
     13 # display JSON string
     14 person_json

NameError: name 'json' is not defined

We get a NameError: name 'json' is not defined. This is because we have imported the josn module with the name json but we’re trying to use it using the name json.

To fix this error, you can either access json using the name that you have used in the import statement or import json without an alias. Note that generally, the convention is to import the json module without any aliases.

Conclusion

In conclusion, encountering a NameError: name 'json' is not defined error can be frustrating, but it is a common issue that can be easily fixed. By following the steps outlined in this tutorial, you should now have a better understanding of what causes this error and how to resolve it. Remember to always check your code for typos and syntax errors, and to import any necessary modules before using them in your code. With these tips in mind, you should be able to tackle any NameError errors that come your way.

You might also be interested in –

  • How to Fix – NameError: name ‘heapq’ is not defined
  • Convert Python Dictionary to JSON
  • Write a Pandas DataFrame to a JSON File
  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

Table of Contents
Hide
  1. What is ImportError: cannot import name ‘json’ from itsdangerous?
  2. How to fix ImportError: cannot import name ‘json’ from itsdangerous
    1. Solution 1 – Upgrade the Flask to latest version > 2
    2. Solution 2 – Upgrade Flask to 1.1.4 and downgrade the markupsafe to 2.0.1
    3. Solution 3 – Downgrade itsdangerous to 2.0.1
  3. Conclusion

If you are deploying and running the flask application(1.1.2) using the Docker containers, you will get ImportError: cannot import name ‘json’ from itsdangerous

In this article, we will look at what is ImportError: cannot import name ‘json’ from itsdangerous means and how to fix the issue.

The issue is faced mainly when you use the Python application and running the application with Flask version 1.1.2 or Flask version 1.1.4.

The Flask application has a dependency on the below two packages.

  • MarkupSafe comes with Jinja. It escapes untrusted input when rendering templates to avoid injection attacks.
  • ItsDangerous securely signs data to ensure its integrity. This is used to protect Flask’s session cookie.

Even if you upgrade the Flask version to 1.1.4 you will still get ‘soft_unicode error.

This issue seems to be related: ImportError: cannot import name ‘soft_unicode’ from ‘markupsafe’ in Release 1.38.0 #3661

It looks the issue is due to an upgrade in MarkupSafe:2.1.0 where they have removed soft_unicode. Checkout the Release Notes for more details. 

It is also a breaking change in markupsafe and jinja not specifying an upper version bound pallets/markupsafe#286

How to fix ImportError: cannot import name ‘json’ from itsdangerous

Solution 1 – Upgrade the Flask to latest version > 2

The best way to resolve this issue is to upgrade the Flask to the latest version, i.e, 2.0.1 or above.

This will be a major upgrade if you are using the older Flask version like 1.1.2 and may have to test the entire application.

As an immediate solution If you still want to stick with the same Flask version and resolve this error, then you can go through the below solutions.

Solution 2 – Upgrade Flask to 1.1.4 and downgrade the markupsafe to 2.0.1

The issue can be fixed by upgrading the Flask version to 1.1.4 or above. However, you will face another issue after upgrading to 1.1.4, which is ImportError: cannot import name ‘soft_unicode’ from ‘markupsafe’, and that can be fixed by downgrading the markupsafe to version 2.0.1 as shown below.

  1. Upgrade the Flask version from 1.1.2 to 1.1.4 
  2. Downgrade the markupsafe to 2.0.1

Commands to upgrade the Flask version and downgrade the markupsafe library.

pip install Flask==1.1.4
pip install markupsafe==2.0.1

Solution 3 – Downgrade itsdangerous to 2.0.1

Flask 1.1.2 is set up to require itsdangerous >= 0.24. The latest released (itsdangerous) version (2.10) deprecated the JSON API.

If you would want to continue using Flask 1.1.2, you need to require at most itsdangerous 2.0.1 (not 2.10). You can do this by adding itsdangerous==2.0.1 to your requirements.txt file. This will downgrade the version of itsdangerous package

pip install itsdangerous==2.0.1

Refer itsdangerous 2.10 changelog for more details.

Conclusion

If you are deploying and running the flask application with 1.1.2 version by using the Docker containers, you will get ImportError: cannot import name ‘json’ from itsdangerous

The Flask version 1.1.2 has a dependency on markupsafe and itsdangerous packages. The issue is with MarkupSafe:2.1.0 where they have removed soft_unicode.

If you are using Flask version 1.1.2, you can fix the issue by downgrading the itsdangerous version to 2.0.1

If you have upgraded to Flask version 1.1.4 and facing a soft_unicode error then you can downgrade the markupsafe to version 2.0.1

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Здравствуйте. Почему-то не получается загрузить JSON содержимое

import json
jsdata = "{'name': 'Jack'}"
data = json.load(jsdata)
print(data.name)
Traceback (most recent call last):
  File "/home/ubuntu/workspace/Untitled1.py", line 3, in <module>
    data = json.load(jsdata)
  File "/usr/lib/python2.7/json/__init__.py", line 286, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'

This error occurs when you try to use the json module without importing it first. You can solve this error by importing the module using the import keyword. For example,

import json
lst = [1, 2, 3]
json_str = json.dumps(lst)

This tutorial will go through how to solve the error with code examples.


Table of contents

  • NameError: name ‘json’ is not defined
  • Example
    • Solution #1: Import json
    • Solution #2: Use the from keyword
  • Summary

NameError: name ‘json’ is not defined

Python raises the NameError when it cannot recognise a name in our program. In other words, the name we are trying to use is not defined in the local or global scope. A name can be related to a built-in function, module, or something we define in our programs, like a variable or a function.

The error typically arises when:

  • We misspell a name
  • We do not define a variable or function
  • We do not import a module

In this tutorial, the source of the error NameError: name ‘json‘ is not defined is usually due to not importing the module. Let’s look at an example.

Example

JSON stands for JavaScript Object Notation and is a lightweight format for storing and transporting data inspired by the syntax to define JavaScript objects. The module json contains functions for working with JSON data.

The json module is built-in, which means it comes with Python.

Let’s look at an example of using the loads() method to parse a JSON string.

# JSON string:
x =  '{ "name":"Michalis", "age":23, "city":"Athens"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:
print(y["age"])

The json.loads() method returns a Python dictionary. We can access a value in the dictionary by specifying its key. Let’s try to run the code to get the age value:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [1], in <cell line: 5>()
      2 x =  '{ "name":"Michalis", "age":23, "city":"Athens"}'
      4 # parse x:
----> 5 y = json.loads(x)
      7 # the result is a Python dictionary:
      8 print(y["age"])

NameError: name 'json' is not defined

The error occurred because we did not import the json module. Although json is a built-in module, we still have to import it.

Solution #1: Import json

We can import the module by putting an import statement at the top of the program. Let’s look at the updated code:

import json

# JSON string:
x =  '{ "name":"Michalis", "age":23, "city":"Athens"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:
print(y["age"])

Let’s run the code to get the age value from the dictionary:

23

Solution #2: Use the from keyword

We can also use the from keyword to import a specific variable, class or function from a module. In this case, we want to import the loads() method from the json module. Using the from keyword means we do not have to specify the module in the rest of the program, we only need to call the loads() method.

Let’s look at the revised code:

from json import loads

# JSON string:
x =  '{ "name":"Michalis", "age":23, "city":"Athens"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:
print(y["age"])

Let’s run the code to get the age value from the dictionary:

23

Summary

Congratulations on reading to the end of this tutorial!

For further reading on NameErrors, go to the article: How to Solve Python NameError: name ‘os’ is not defined

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Immergas ошибка е38
  • Immergas ошибка е10 как исправить
  • Immergas ошибка е02
  • Immergas ошибка e98

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии