Python json get key and value

How to find a particular JSON value by key?

How can I find all P1 ‘s value without it iterating all JSON? P.S.: P1 can be anywhere in the JSON. If no method can do this, can you tell me how to iterate through the JSON?

If it can be anywhere in the set of nested structures, then you’re going to have to look through all of it. That’s just how reality works.

9 Answers 9

As I said in my other answer, I don’t think there is a way of finding all values associated with the «P1» key without iterating over the whole structure. However I’ve come up with even better way to do that which came to me while looking at @Mike Brennan’s answer to another JSON-related question How to get string objects instead of Unicode from JSON?

The basic idea is to use the object_hook parameter that json.loads() accepts just to watch what is being decoded and check for the sought-after value.

Note: This will only work if the representation is of a JSON object (i.e. something enclosed in curly braces <> ), as in your sample.

from __future__ import print_function import json def find_values(id, json_repr): results = [] def _decode_dict(a_dict): try: results.append(a_dict[id]) except KeyError: pass return a_dict json.loads(json_repr, object_hook=_decode_dict) # Return value ignored. return results json_repr = ', "P3": []>' print(find_values('P1', json_repr)) 

I had the same issue just the other day. I wound up just searching through the entire object and accounted for both lists and dicts. The following snippets allows you to search for the first occurrence of a multiple keys.

import json def deep_search(needles, haystack): found = <> if type(needles) != type([]): needles = [needles] if type(haystack) == type(dict()): for needle in needles: if needle in haystack.keys(): found[needle] = haystack[needle] elif len(haystack.keys()) > 0: for key in haystack.keys(): result = deep_search(needle, haystackPython json get key and value) if result: for k, v in result.items(): found[k] = v elif type(haystack) == type([]): for node in haystack: result = deep_search(needles, node) if result: for k, v in result.items(): found[k] = v return found deep_search(["P1", "P3"], json.loads(json_string)) 

It returns a dict with the keys being the keys searched for. Haystack is expected to be a Python object already, so you have to do json.loads before passing it to deep_search.

Читайте также:  Вывести индекс элемента строки python

Any comments for optimization are welcomed!

Источник

How can I get ‘key’ and ‘value’ from parsed JSON in python [closed]

Today I’m trying to do little tricky thing. I’m trying to get key and value from parsed JSON like this:

for data in json: print(data.key) # This should return the test1 string print(data.value) # This sould return the test2 string 

2 Answers 2

What you receive when you load json data, is native Python Dict, or List. When you’re iterating over a list of dictionaries as you do here, data is a dict.

To extract a value from a dict, you need to look up the key by its name, in your instance: ‘minecraft.net’, ‘session.minecraft.net’, ‘account.mojang.com’, .

Python dictionaries are accessed like so: data[«minecraft.net»] (returns «green»)

Easiest to do would be (following your setup):

for data in json: for key, value in data.items(): print(key) print(value) 
for dictionary in list: for key, value in dictionary.items(): print(key) print(value) 

Unclear in the question, but variable ‘json’ was a file-like object. Resolved issue with:

This assumes that json is indeed a list of dictionaries, import native library called «json» and use: json.loads() to get it working properly.

Your code is returning this discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: ‘bytes’ object has no attribute ‘items’

Then it seems your «json» variable is not a list, it is a bytes object. How do you load the json data? Try using: with open(«file.json») as f: json = json.load(f.read())

Then try using json = json.load(json) to utilize the JSON library to turn that bytes-like object into a list of dicts 🙂 (note: json.loads() expects a string, but json.load() expects a bytes-like object)

json = [, , , , < 'sessionserver.mojang.com': 'red'>, , , ] for data in json: for key in data: print(key) print(dataPython json get key and value) 
green session.minecraft.net green account.mojang.com green authserver.mojang.com green sessionserver.mojang.com red api.mojang.com green textures.minecraft.net green mojang.com green PS C:\Users\jonas\OneDrive\Desktop\seconddesktop\newLocalWebsite> & C:/Users/jonas/AppData/Local/Programs/Python/Python39/python.exe c:/Users/jonas/OneDrive/Desktop/seconddesktop/newLocalWebsite/react-folder/src/components/test.py minecraft.net green session.minecraft.net green account.mojang.com green authserver.mojang.com green sessionserver.mojang.com red api.mojang.com green textures.minecraft.net green mojang.com green 

By iterating over the dict you get the keys, by writing dataPython json get key and value , you get the values!

Источник

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 get list of values of a single key from JSON using Python

Please edit your question and add what have you tried so far and the error that you got. Also we need more info about your question, is that just a list or json data?

4 Answers 4

for element in data['tr']: print element['name'] print element['promoted_content'] print element['query'] print element['events'] 

You are asking, «I have a list of dictionaries. Each dictionary has a key «name» . How do I get a list of values of all those keys?»

Basics

  • Access list elements using an index in brackets. a[0] is the first element of a list.
  • Access dictionary values using the key in brackets. a[«name»] is this_value from .
  • Aggregate values with a loop like so:
aggregator = [] for item in a_list: aggregator.append(value_calculated_from(item)) 

Problems with question

your_list doesn’t have the square brackets paired up.

outer_dictionary = your_list[0] list_of_dictionaries = outer_dictionary['tr'] 

Answer

You can get the list of values of «name»:

names = [] for dictionary in list_of_dictionaries: if "name" in dictionary: names.append(dictionary["name"]) 

@Kevin-Guan, I read his comment to mean he had done that already with loads(). Afzal, are you asking how to get this data into a Python variable or how to extract the «name» values once the JSON is in a variable?

Yes, I think he knows about that. But if you’re going to post a full answer, the full solution about the problem is needed.

I see your data was not formatted completely(before editing)- so i would go for regex-Below code extracts all name from the supplied json STRING(just enclose «»»»»»)

import re data="""[< "tr": [< "name": "#For5Rs", "promoted_content": null, "query": "%23For5Rs", "events": null >, < "name": "Javed Bashir", "promoted_content": null, "query": "%22Javed+Bashir%22", "events": null >, < "name": "Milan Luthria", "promoted_content": null, "query": "%22Milan+Luthria%22", "events": null >, < "name": "Vidya Balan", "promoted_content": null, "query": "%22Vidya+Balan%22", "events": null >], "as_of": "2013-08-16T10:31:35Z", "created_at": "2013-08-16T10:20:41Z", "locations": [< "name": "India", "woeid": 23424848 >] """ names=re.findall(r'(?<="name":\s").+(?=",[\s\S]+"promoted_content")',data) print names 
['#For5Rs', 'Javed Bashir', 'Milan Luthria', 'Vidya Balan'] 

Источник

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.

Источник

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