Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is a valid JSON in python

Tags:

python

json

linux

I have a python script providing command line / output in console on remote 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. I tried

if "value" in line:
    json.loads(line)

it is not reading and even

json.dumps(line)

not giving output ?

like image 396
Error_Coding Avatar asked Jul 06 '26 00:07

Error_Coding


1 Answers

You can use try except clause to check if a string is actually 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. You can use this tool JSONLint to verify if your JSON is a valid JSON.

like image 109
shaktimaan Avatar answered Jul 08 '26 16:07

shaktimaan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!