检查字符串在Python中是否有效JSON
JSON是一种文本格式,用于在各种计算机程序之间轻松交换数据。它具有Python可以验证的特定格式。在本文中,我们将考虑一个字符串,并使用JSON模块验证该字符串是否表示有效的JSON格式。
创建JSON对象
json模块具有称为load的方法。它加载一个有效的json字符串以创建一个Json对象。在此示例中,我们加载字符串并检查加载JSON对象是否没有错误。如果有错误,我们认为JSON字符串无效。
示例
import json Astring= '{"Mon" : "2pm", "Wed" : "9pm" ,"Fri" : "6pm"}' # Given string print("Given string", Astring) # Validate JSON try: json_obj = json.loads(Astring) print("A valid JSON") except ValueError as e: print("Not a valid JSON") # Checking again Astring= '{"Mon" : 2pm, "Wed" : "9pm" ,"Fri" : "6pm"}' # Given string print("Given string", Astring) # Validate JSON try: json_obj = json.loads(Astring) print("A valid JSON") except ValueError as e: print("Not a valid JSON") # Nested levels Astring = '{ "Timetable": {"Mon" : "2pm", "Wed" : "9pm"}}' # Given string print("Given string", Astring) # Validate JSON try: json_obj = json.loads(Astring) print("A valid JSON") except ValueError as e: print("Not a valid JSON")
输出结果
运行上面的代码给我们以下结果-
Given string {"Mon" : "2pm", "Wed" : "9pm" ,"Fri" : "6pm"} A valid JSON Given string {"Mon" : 2pm, "Wed" : "9pm" ,"Fri" : "6pm"} Not a valid JSON Given string { "Timetable": {"Mon" : "2pm", "Wed" : "9pm"}} A valid JSON