oldoc63 / learningDS

Learning DS with Codecademy and Books
0 stars 0 forks source link

Reading a JSON File #363

Open oldoc63 opened 1 year ago

oldoc63 commented 1 year ago

CSV insn't the only file format that Python has a built-in library for. We can also use Python's file tools to read and write JSON. JSON an abbreviation of JavaScript Object Notation, is a file format inspired by the programming language JavaScript. The name, like CSV is a bit of a misnomer - some JSON is not valid JavaScript (and plenty JavaScript is not valid JSON).

JSON format is endearingly similar to Python dictionary syntax, and so JSON files might be easy to read from a Python developer standpoint. Nonetheless, Python comes with a json package that will help us parse JSON files into actual Python dictionaries.

oldoc63 commented 1 year ago

First we import the json package. We opened the file using our trusty open command. Since we're opening it in read-mode we just need to pass the file name. We save the file in the temporary variable purchase_json.

We continue by parsing purchase_json using json.load(), creating a Python dictionary out of the file. Saving the results into purchase_data means we can interact with it. We print out one of the values of the JSON file by keying into the purchase_data object.