[英]How to check if a string is a valid JSON in python
I have a python script providing command line / output in console on remote linux. 我有一个python脚本在远程linux的控制台中提供命令行/输出。 I have another script which is reading this output on local machine.
我有另一个脚本,它在本地机器上读取此输出。 Output is in below format:
输出格式如下:
ABC: NEG
BCD: NEG
FGH: POS
{aa:bb:cc:dd:ee{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}}
notice last line is in json format, now I want to check which line is in json format of the output. 注意最后一行是json格式,现在我想检查哪一行是json格式的输出。 I tried
我试过了
if "value" in line:
json.loads(line)
it is not reading and even 它不是阅读甚至是
json.dumps(line)
json.dumps(线)
not giving output ? 没有输出?
You can use try except clause to check if a string is actually json: 您可以使用try except子句来检查字符串是否实际上是json:
import json
line = '<what you think is json>'
try:
json_line = json.loads(line)
except ValueError:
print("not a json")
In your above code the last line is not a valid JSON. 在上面的代码中,最后一行不是有效的JSON。 You can use this tool JSONLint to verify if your JSON is a valid JSON.
您可以使用此工具JSONLint来验证您的JSON是否是有效的JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.