Python get key from json

Получите все ключи и ценности от объекта JSON в Python

В этом учебном пособии Python мы посмотрим, как мы можем получить все ключи в этом объекте JSON, а также … с меткой Python.

В этом Python Учебное пособие Мы узнаем, как мы можем получить все ключи в этом объекте JSON, а также все значения клавиш.

хорошо, так что позвольте мне начать, позвольте мне взять один пустой файл Python здесь, так Ага Итак, дайте мне сначала сохранить этот файл, как example.py.

Загрузить json

Как это JSON, мне нужно импортировать этот пакет под названием JSON Отказ Это позволяет играть с json. . Тогда он доступен в этом конкретном файле Python.

Право, так что возьмите этот путь к файлу и попробуйте открыть это с Открыть как файл JSON Отказ

with open("C:\\pythonPrograms\\example.json") as jsonFile:

Это сделает JSON декодирование Отказ Наш файл json выглядит так:

Вам нужно дать имя файла, так что это мое имя файла. Он должен иметь двойные скольжения, а не одну косулью, поэтому, как только мы имеем это, используя библиотеку JSON, которую мы импортировали, вам нужно загрузить объект JSON. Пойдем.

Получить ключи и ценности

Использование функции нагрузки JSON File, это позвольте мне держать его в переменную, называемые данными.

Читайте также:  Css on touch event

Тогда у вас есть питон объект . Теперь вы можете получить ключи и значения. Ниже приведен код зависит от того, как выглядит ваш файл JSON. В нашем файле JSON есть заголовок под названием Emp_Details.

jsonData = data["emp_details"] keys = x.keys() values = x.values()
import json with open("test.json") as jsonFile: data = json.load(jsonFile) jsonData = data["emp_details"] for x in jsonData: keys = x.keys() print(keys) values = x.values() print(values)
 dict_keys(['name', 'id']) dict_values(['a', '123']) dict_keys(['name', 'id']) dict_values(['b', '345'])

Если вы хотите, вы можете закрутить клавиши и значения внутри петли, чтобы сделать форматирование.

Здесь мы используем для петли Итерации по ключам и значениям. Если ваш файл JSON невелик, как тот пример, вы не обязательно используете петлю.

Читайте ещё по теме:

Источник

Get all keys and values from json object in Python

In this Python tutorial we are going to see how we can get all the keys in this json object and also all the values of the keys. okay so let me get started let me take one empty python file
here, so yeah so let me save this file first as example.py.

Load json

As it is a json i need to import this package called json. This lets you play around with json. Then it is available in this particular Python file.

with open("C:\\pythonPrograms\\example.json") as jsonFile: 
 "emp_details":[ "name": "a", "id": "123" >, "name":"b", "id":"345" > ] > 

Let

You need to give the file name, so this is my file name. It should have double slashes not the single slash, so once we have this using the json library that we have imported you need to load the json object. Let’s go.

Get keys and values

Then you have a Python object. Now you can get the keys and values. The code below depends on what your json file looks like. In our json file there’s a header named emp_details.

 jsonData = data["emp_details"] keys = x.keys() values = x.values() 
 import json with open("test.json") as jsonFile: data = json.load(jsonFile) jsonData = data["emp_details"] for x in jsonData: keys = x.keys() print(keys) values = x.values() print(values) 
 dict_keys(['name', 'id']) dict_values(['a', '123']) dict_keys(['name', 'id']) dict_values(['b', '345']) 

If you want, you can loop over the keys and values inside the loop, to do the formatting. Here we use a for loop to iterate over the keys and values. If your json file is small like the one in this example, you don’t necessarily have to use a loop. That’s all 🙂

Источник

How to Extract Data from JSON File in Python?

How to Extract Data from JSON File in Python?

In this tutorial, you will learn how to parse JSON file and extract data from file in python? We will look at how we can use ‘json’ module to read the json object and get the value from json array?

The JSON stands for JavaScript Object Notation and it is a very popular lightweight data-interchanging format. We use the JSON to serialize the data have a key pair value data. The JSON object same looks like dictionaries in python.

So, here we will see how you can read the JSON data in python and extract the specific data from the file? We will use the ‘json’ python module. You don’t need to install it using the pip because it’s an in-built module. You can just use it by importing it into the file.

Let’s get started to play with json data in python.

Parse JSON Object in Python

In this example, we will parse the simple json object string that we will create in python. So first thing you need to import the ‘json‘ module into the file.

Then create a simple json object string in python and assign it to a variable.

Now we will use the loads() function from ‘json‘ module to load the json data from the variable. We store the json data as a string in python with quotes notation.

And then we will use the dumps() function from the ‘json‘ module to convert the python string to a JSON object. Now it’s ready to print your json object in python. See the following example code.

In the above code, we print the json data and used the indent for indentation. You can also use the sort in print to sorting the result. So when you run the above code you will get the output like below.

Output:

Now if you want to iterate this json data then just simply use the loop to prin each data one by one. I’m going to use for loop to print it.

Output:
python: 1 php: 2 c: 3 vb: 4 perl: 5

Hope you understand the basic of parsing the JSON object in python and print the value from it. Let’s now work with file to extract data it using the ‘json’ python module.

Lexa Django Template

Parse JSON File in Python

In this example, we will learn how to extract data from json file in python. In the above example, we saw the parse simple JSON object and in this example, we will do the same but first, we will create a json file with .json extension.

Let’s create the json_data.json file with the following JSON object OR you can download it from here. And you can also use my JSON formatter tool to minify and beautify json object and download it.

To Load this json file in python, we will first open this file as a read mode using the open() function.

The above code will print your json data from the file. It will store the JSON as python dictionaries, you can check the type of json_load variable using the type(json_load) .

Now you can use it in python and get the data from it which you want to use in the program. You can get the specific index data or you can loop through all data.

Let’s look at how to extract specific data from json file object in python that we have printed above example.

Extract Specific Data from JSON File

As we have store json in the json_data variable, now we will use this variable to get the specific value from the json array.

I will use the key represent to index to get that value from JSON object.

For example, if I want to print all ‘languages‘ from the ‘web‘ JSON object then I will use the following code.

Output:

If you want to get only first language the use the following

Output:

Just use the index of the array to get any languages and I’m sure you know that array index always starts from ‘0’.

JSON Array Loop Through Data

As you see in the above example, we fetched all languages and print them as objects. Now if you want to loop the value and print each language one by one then we will use the for loop to do it.

Output:
1 PHP https://www.php.net/ 2 Python https://www.python.org/ 3 Java https://www.java.com/en/

Hope you understand the tutorial how to extract the data from JSON file in python and how to fetch specific data from JSON array.

If you have questions please let me know in the comment section I would love to help you with that.

Источник

Оцените статью