Получить элементы json python

Как вывести значение из json?

Изначально json уже содержит нечитаемый набор данных.

Есть вот такой набор данных полученный с помощью json.dumps:

Получаю я его через свой api с сайта таким вот способом:

Необходимо вывести например «num».

Насчет правильности использования dumps заместо load или loads не уверен.
Но с последними у меня всегда какие-то ошибки.
Например при таком случае:

the JSON object must be str, not ‘dict’

При том как с dumps не получается обратиться к элементам.

string indices must be integers

Tark

Внезапно PHP нет, а с ним было бы проще, ха-ха.

Грубо говоря, json.dumps конвертирует словарь в строку. json.loads конвертирует строку в словарь. Словарь — «ассоциативный массив». Но в вашем словаре ключ users возвращает список (настоящий, неассоциативный массив). Если там есть данные, то после выполнения

к нему можно обратиться с помощью конструкции

Где 0 — элемент списка, данные с которого нужно получить. Массивы, ну вы знаете. Не забудьте проверить, есть ли в json ключ users и не нулевой ли длины этот список. Успехов!

kolumbou

Был бы еще благодарен за совет как тогда вывести значение не только первого [0] словарь как в вашем примере, а сразу со всех?
Пробовал и 0: и просто : — всегда ругается на «list indices must be integers or slices, not str».

Tark

Это список. Смотря что вам нужно сделать)

if 'users' in media: for user in media['users']: print(user['num'])

Tark

Давайте так. В вашем примере описан словарь. Доступ к элементам по ключу (не по индексу!). media[‘size’] вернёт 200, например. media[‘users’] — это список. Доступ к элементам по индексу, начиная с 0 (не по ключу!). Элемент media[‘users’][0] — это опять словарь, доступ к элементам по ключу. media[‘users’][0][‘name’] вернёт myname, например.

Если вам интерпретатор показывает ошибку «list indices must be integers or slices, not str», значит вы обращаетесь к списку неверным образом. Возможно, вместо строго целого числа вы пытаетесь запросить строку. media[‘users’][‘0’][‘name’] вернёт такую ошибку, тогда как media[‘users’][0][‘name’] покажет имя.

Квадратные скобочки — список (не ассоциативный массив, доступ к элементам по индексу)
Фигурные скобочки — словарь (ассоциативный массив, доступ к элементам по ключу)
Любой из этих типов — итерируемый, каждый из них можно перебрать в цикле. Правда, есть одно отличие: в стандартном цикле список будет выдавать элемент, а словарь — ключ.

Источник

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.

Источник

Читайте также:  Telegram bot java telegrambots
Оцените статью