CSV and JSON files · 14 / 15 Exercise Medium

Validating JSON

Objective

Create a Python program that checks whether a text is valid JSON, catching the error raised by json.loads.

Instructions

  • Read a line of text.
  • Try to convert it with json.loads inside a try, and catch json.JSONDecodeError.
  • If it is not valid JSON, show Invalid JSON.
  • If it is valid and the result is a dictionary (a JSON object), show Object with K keys.
  • If it is valid but not an object (a list, a number, a text…), show Valid, but not an object.
Input
{"a": 1, "b": 2}
Output
Object with 2 keys

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise