You can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.
In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.
Answer from John Flatness on Stack OverflowYou can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.
In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.
Example Python script returns a boolean if a string is valid json:
import json
def is_json(myjson):
try:
json.loads(myjson)
except ValueError as e:
return False
return True
Which prints:
print is_json("{}") #prints True
print is_json("{asdf}") #prints False
print is_json('{ "age":100}') #prints True
print is_json("{'age':100 }") #prints False
print is_json("{\"age\":100 }") #prints True
print is_json('{"age":100 }') #prints True
print is_json('{"foo":[5,6.8],"foo":"bar"}') #prints True
Convert a JSON string to a Python dictionary:
import json
mydict = json.loads('{"foo":"bar"}')
print(mydict['foo']) #prints bar
mylist = json.loads("[5,6,7]")
print(mylist)
[5, 6, 7]
Convert a python object to JSON string:
foo = {}
foo['gummy'] = 'bear'
print(json.dumps(foo)) #prints {"gummy": "bear"}
If you want access to low-level parsing, don't roll your own, use an existing library: http://www.json.org/
Great tutorial on python JSON module: https://pymotw.com/2/json/
Is String JSON and show syntax errors and error messages:
sudo cpan JSON::XS
echo '{"foo":[5,6.8],"foo":"bar" bar}' > myjson.json
json_xs -t none < myjson.json
Prints:
, or } expected while parsing object/hash, at character offset 28 (before "bar}
at /usr/local/bin/json_xs line 183, <STDIN> line 1.
json_xs is capable of syntax checking, parsing, prittifying, encoding, decoding and more:
https://metacpan.org/pod/json_xs
Ok... This is a little complicated... So... Sorry in advance
I have a function that returns attributes of a video file (FFprobe) in a JSON object, and then a little factory that parses the JSON looking for specific attributes, and running if statements on those attributes.
I.E. One of attributes in the JSON is subtitle format. So if the subtitle format != a desired format, then set a variable that is used in another format for encoding the subtitle to the desired format
The issue that I have run into so that sometimes those attributes (like subtitle) don't exist in the JSON because they do not exist in the file.
So I sort of need to check if the attribute in the JSON exists, before I check to see if if that attribute is the desired attribute and start setting variables
How do I do this?
Would it be as simple as:
json_object= json.loads(studentJson)
if "subtitle_format" in json_object:
print("Key exist in json_object")
print(subtitle_format["ASS"], " is the subtitle format")
else:
print("Key doesn't exist in JSON data")If yes, would I get yelled at if the if statement had a few layers? Psudo:
if subtitle_format in json_object:
if subtitle_format == ass
if subtitle_format == english
encode Verify if a String is JSON in python? - Stack Overflow
How to check if a string is a valid JSON in python - Stack Overflow
Python: check if string is JSON without raising an exception? - Stack Overflow
How to Check if key Error key exist in a JSON String Python
Videos
The correct answer is: stop NOT wanting to catch the ValueError.
Example Python script returns a boolean if a string is valid json:
import json
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError as e:
return False
return True
print(is_json('{}')) # prints True
print(is_json('{asdf}')) # prints False
print(is_json('{"age":100}')) # prints True
print(is_json('{'age':100 }')) # prints False
print(is_json('{"age":100 }')) # prints True
To verify the string would require parsing it - so if you checked then converted it would literally take twice as long. Catching the exception is the best way. Interestingly, you can still use an if-else style expression:
try:
json_object = json.loads(json_string)
except ValueError as e:
pass # invalid json
else:
pass # valid json
More compact way should be like this. Json lib process only str, bytes or bytearray structures, so only consider them. Instead of if len(text)==0, if not text is much faster for long strings, we don't want to know length of text. Json lib may raise JsonDecoderError. First last characters of text can be checked back-reference with regex but I tried possible edge cases such as '{]' and '[}', they don't fail.
def is_json(text: str) -> bool:
from json import loads, JSONDecodeError
if not isinstance(text, (str, bytes, bytearray)):
return False
if not text:
return False
text = text.strip()
if text[0] in {'{', '['} and text[-1] in {'}', ']'}:
try:
loads(text)
except (ValueError, TypeError, JSONDecodeError):
return False
else:
return True
else:
return False
EDIT: We should check whether text is empty or not, not to raise IndexError.
def is_json(text: str) -> bool:
if not isinstance(text, (str, bytes, bytearray)):
return False
if not text:
return False
text = text.strip()
if text:
if text[0] in {'{', '['} and text[-1] in {'}', ']'}:
try:
loads(text)
except (ValueError, TypeError, JSONDecodeError):
return False
else:
return True
else:
return False
return False
for speed issue you can use multiprocessing to speed up the parsing , for example by utilizing 5 workers in multiprocessing you parse 5 string at a time instead of one
if i understand second part of question , for custom exception do something like this to get custom error for different error that return by json:
def parse_json(string):
try:
return json.loads(string)
except exception1 as ex1:
print(ex1)
return string
except exception2 as ex2:
print(ex2)
return string
exc....
or if you don't want to get any exception on error raising do this , just give it a pass to do nothing , not showing up anything:
def parse_json(string):
try:
return json.loads(string)
except exception1 as ex1:
pass
first, your input isn't json. Json uses double quotes. But suppose you successfully loaded it with json, it's now a dictionary, called d.
Then you can scan all sub-dicts of d and test serial key against your value, stopping when found using any and a generator comprehension:
print(any(sd['serial']=='00000000762c1d3c' for sd in d['device']))
returns True if serial found False otherwise.
date['device'] contains a list of objects, so you should treat it as such and iterate over them:
for element in data['device']:
if element['serial'] == '00000000762c1d3c':
print 'there'
print element['registered_id']
break
else:
print 'not there'
This is using the somehow lesser-known for-else construct: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
You are checking data as a dictionary object. When checking using if check in data it checks if data object have a key matching the value of the check variable (data.keys() to list all keys).
One easy way would be to use if check in data["players"].__str__() which will convert value to a string and search for the match.
If you want to make sure that check value only checks for the steam64 values, you can write a simple function that will iterate over all "players" and will check their "steam64" values. Another solution would be to make list of "steam64" values for faster and easier checking.
You can use any() to check if value of steam64 key is there.
For example:
import json
def check_value(data, val):
return any(player['steam64']==val for player in data['players'])
with open('banneds.json', 'r') as f_in:
data = json.load(f_in)
print(check_value(data, 76561198046619692))
Prints:
True