- Как найти конкретное значение JSON по ключу?
- 9 ответов
- Python Check if key exists in JSON and iterate the JSON array
- Check if the key exists or not in JSON
- Check if there is a value for a key in JSON
- Return default value if the key is missing
- Python Find if the nested key exists in JSON
- Iterate JSON Array
- So What Do You Think?
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
- Check if a Key Exists in a JSON String or not in Python
- Python Program to Check if a Key Exists in a JSON String
Как найти конкретное значение JSON по ключу?
Как я могу найти все P1 ценность без этого итерации все JSON?
PS: P1 может быть где угодно в JSON.
Если никакой метод не может сделать это, вы можете сказать мне, как перебрать json?
9 ответов
Мой подход к этой проблеме был бы другим.
Поскольку JSON не разрешает поиск в глубину, конвертируйте json в объект Python, передавайте его в XML-декодер и затем извлекайте узел, который вы собираетесь искать
from xml.dom.minidom import parseString import json def bar(somejson, key): def val(node): # Searches for the next Element Node containing Value e = node.nextSibling while e and e.nodeType != e.ELEMENT_NODE: e = e.nextSibling return (e.getElementsByTagName('string')[0].firstChild.nodeValue if e else None) # parse the JSON as XML foo_dom = parseString(xmlrpclib.dumps((json.loads(somejson),))) # and then search all the name tags which are P1's # and use the val user function to get the value return [val(node) for node in foo_dom.getElementsByTagName('name') if node.firstChild.nodeValue in key] bar(foo, 'P1') [u'cccc', u'aaa', u'ss'] bar(foo, ('P1','P2')) [u'cccc', u'cccc', u'aaa', u'ss']
Как я уже говорил в своем другом ответе, я не думаю, что есть способ найти все значения, связанные с «P1» ключ без итерации по всей структуре. Однако я нашел еще лучший способ сделать то, что пришло мне в голову, глядя на принятый ответ на другой вопрос. Как получить строковые объекты вместо Unicode из JSON?
Основная идея заключается в использовании object_hook параметр, который json.loads() принимает только для просмотра того, что декодируется, и проверки искомого значения. Примечание: это будет работать только если представление в формате JSON Object (то есть что-то, заключенное в фигурные скобки <> ), как в вашем образце JSON.
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)
У меня была такая же проблема только на днях. Я в итоге просто перебрал весь объект и учел как списки, так и диктанты. Следующие фрагменты позволяют вам искать первое вхождение нескольких ключей.
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 поиск ключа) 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))
Он возвращает dict с ключами, являющимися ключами, которые искали. Ожидается, что Haystack уже будет объектом Python, поэтому вам нужно выполнить json.loads, прежде чем передавать его в deep_search.
Любые комментарии по оптимизации приветствуются!
Python Check if key exists in JSON and iterate the JSON array
In this article, we will see how to perform the following JSON operations using Python.
- Check if the key exists or not in JSON
- Check if there is a value for a key, and return a default value if the key is missing
- Iterate JSON array
Further Reading:
Check if the key exists or not in JSON
Let’s assume you received the following student, JSON. And you wanted to check if the percentage key is present or not in JSON data. if it is present directly to access its value instead of iterating the entire JSON.
import json studentJson ="""< "id": 1, "name": "john wick", "class": 8, "percentage": 75, "email": "jhon@pynative.com" >""" print("Checking if percentage key exists in JSON") student = json.loads(studentJson) if "percentage" in student: print("Key exist in JSON data") print(student["name"], "marks is: ", student["percentage"]) else: print("Key doesn't exist in JSON data")
Checking if percentage key exists in JSON Key exist in JSON data john wick marks is: 75
Note: We used json.loads() method to convert JSON encoded data into a Python dictionary. After turning JSON data into a dictionary, we can check if a key exists or not.
Check if there is a value for a key in JSON
We need a value of the key to be present in JSON so we can use this value in our system. In this case, we need to be sure that value is present for a key, and if it is none or not present, we use the default value.
Example to check if there is a value for a key in JSON
import json studentJson ="""< "id": 1, "name": "john wick", "class": null, "percentage": 75, "email": "jhon@pynative.com" >""" student = json.loads(studentJson) if not (student.get('email') is None): print("value is present for given JSON key") print(student.get('email')) else: print("value is not present for given JSON key")
value is present for given JSON key jhon@pynative.com
Return default value if the key is missing
Let’s see how to use a default value if the value is not present for a key. As you know, the json.loads method converts JSON data into Python dict so we can use the get method of dict class to assign a default value to the key if the value is missing.
import json studentJson ="""< "id": 1, "name": "john wick", "class": null, "percentage": 75, "email": "jhon@pynative.com" >""" student = json.loads(studentJson) if not (student.get('subject') is None): print("value is present for given JSON key") print(student.get('subject')) else: print("using a default value for a given key") print(student.get('subject', 'Science'))
value is not present for given JSON key using a default value for a given key Science
Python Find if the nested key exists in JSON
Most of the time, JSON contains so many nested keys. Let’s see how to access nested key-value pairs from JSON directly. Let’s assume you have the following JSON data. and you want to check and access the value of nested key marks.
Example 1: Access nested key directly
If you know that you always have the parent key present, then you can access the nested JSON key directly. In this case, we always have ‘class‘ and ‘student‘ keys so we can access nested key marks directly.
import json sampleJson = """ < "class":< "student":< "name":"jhon", "marks":< "physics":70, "mathematics":80 >> > >""" print("Checking if nested JSON key exists or not") sampleDict = json.loads(sampleJson) if 'marks' in sampleDict['class']['student']: print("Student Marks are") print("Printing nested JSON key directly") print(sampleDict['class']['student']['marks'])
Checking if nested JSON key exists or not Student Marks are Printing nested JSON key directly
Example 2: Access nested key using nested if statement
If you are not sure whether you always have the parent key present, in such cases, we need to access nested JSON using nested if statement, to avoid any exceptions.
import json sampleJson = """ < "class":< "student":< "name":"jhon", "marks":< "physics": 70, "mathematics": 80 >> > >""" print("Checking if nested JSON key exists or not") sampleDict = json.loads(sampleJson) if 'class' in sampleDict: if 'student' in sampleDict['class']: if 'marks' in sampleDict['class']['student']: print("Printing nested JSON key-value") print(sampleDict['class']['student']['marks'])
Iterate JSON Array
Many times nested JSON key contains a value in the form of an array or dictionary. In this case, if you need all values, we can iterate the nested JSON array. Let’s see the example.
import json sampleJson = """< "class":< "student":< "name":"jhon", "marks":< "physics": 70, "mathematics": 80 >, "subjects": ["sub1", "sub2", "sub3", "sub4"] > > >""" sampleDict = json.loads(sampleJson) if 'class' in sampleDict: if 'student' in sampleDict['class']: if 'subjects' in sampleDict['class']['student']: print("Iterating JSON array") for sub in sampleDict['class']['student']['subjects']: print(sub)
Iterating JSON array sub1 sub2 sub3 sub4
So What Do You Think?
I want to hear from you. What do you think of this article? Let me know by leaving a comment below.
Also, try to solve the Python JSON Exercise to have a better understanding of Working with JSON Data in Python.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ
Check if a Key Exists in a JSON String or not in Python
In this tutorial, we will learn how to check if a key exists in a JSON (JavaScript Object Notation) string or not using Python.
JSON is a popular and special type of data format used for data manipulation. So, let’s see…..
Python Program to Check if a Key Exists in a JSON String
First, let’s consider the following JSON string.
To detect whether a key exists in the above JSON formatted string or not, you should use the ‘in’ keyword as Python treats the above JSON data as String. See the below code and try to understand:
json_string='' if "website" in json_string: print("The required key is present") else: print("The required key is absent")
The output of the above program will be:
The required key is present
As the ‘website’ key is present in the json_string, so the ‘if’ block is executed.
We can not access the values using the keys in this method. To access the values you should convert the JSON string into a python dictionary by using ‘json.loads()’ method after importing the ‘json’ module. Then you can check whether a key exists in the dictionary or not and if it exists, you can access the value. See the following code.
import json json_string='' python_dict=json.loads(json_string) if "website" in python_dict: print("The required key is present") print("The value is="+str(python_dict["website"])) else: print("The required key is absent")
And below is the output result:
The required key is present The value is=codespeedy