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
Validate JSON data using python - Stack Overflow
JSON string validation in Python - Stack Overflow
How to check if something is in a JSON object before running if statement
I wrote okjson - A fast, simple, and pythonic JSON Schema Validator
Videos
If you haven't check jsonschema library, it can be useful to validate data. JSON Schema is a way to describe the content of JSON. The library just uses the format to make validations based on the given schema.
I made a simple example from basic usage.
import json
from jsonschema import validate
# Describe what kind of json you expect.
schema = {
"type" : "object",
"properties" : {
"description" : {"type" : "string"},
"status" : {"type" : "boolean"},
"value_a" : {"type" : "number"},
"value_b" : {"type" : "number"},
},
}
# Convert json to python object.
my_json = json.loads('{"description": "Hello world!", "status": true, "value_a": 1, "value_b": 3.14}')
# Validate will raise exception if given json is not
# what is described in schema.
validate(instance=my_json, schema=schema)
# print for debug
print(my_json)
As you're using a JSON file, you can use this example:
import json
def validate(filename):
with open(filename) as file:
try:
data = json.load(file) # put JSON-data to a variable
print("Valid JSON") # in case json is valid
return data
except json.decoder.JSONDecodeError:
print("Invalid JSON") # in case json is invalid
» pip install json-checker
By default json.loads accepts '-Infinity', 'Infinity', 'NaN' as values. But you can control this by using parse_constant parameter.
Quoting from the documentation,
if it specified, will be called with one of the following strings: '
-Infinity', 'Infinity', 'NaN'. This can be used to raise an exception if invalid JSON numbers are encountered
You can use parse_constant, documentation says:
if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered.
For example:
import json
s = '{"position": NaN, "score": 0.3}'
def validate(val):
if val == 'NaN':
raise ValueError('Nan is not allowed')
return val
print(json.loads(s, parse_constant=validate))
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