JSON COMPSCI 105 S2 2015 Principles of Computer Science.

Slides:



Advertisements
Similar presentations
Lecture 07 – Iterating through a list of numbers.
Advertisements

Lecture 04 – Classes.  Python has a number of classes built-in  lists, dictionaries, sets, int, float, boolean, strings  We can define our own classes.
Lecture 2 Introduction to C Programming
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Lecture 03 – Sequences of data.  At the end of this lecture, students should be able to:  Define and use functions  Import functions from modules 
COEN 445 Communication Networks and Protocols Lab 4
Week 2 Classes, Objects and lists review Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise.
Guide To UNIX Using Linux Third Edition
Lecture 05 – Classes.  A class provides the definition for the type of an object  Classes can store information in variables  Classes can provide methods.
15-Jul-15 JSON. JSON example “JSON” stands for “JavaScript Object Notation” Despite the name, JSON is a (mostly) language-independent way of specifying.
Classes 2 COMPSCI 105 S Principles of Computer Science.
Exceptions COMPSCI 105 S Principles of Computer Science.
Lecture 2 - Variables, program execution, calculations, print() COMPSCI 101 Principles of Programming.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Lecture 14 - JSON.  Text-based notation for data interchange  Human readable  Object  Unordered set of name-value pairs  { name1 : value1, name2.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
Chapter 6 Functions -- QuickStart. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. What is a function?
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
Introduction. 2COMPSCI Computer Science Fundamentals.
Lecture 06 – Reading and Writing Text Files.  At the end of this lecture, students should be able to:  Read text files  Write text files  Example.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
Classes 1 COMPSCI 105 S Principles of Computer Science.
Compsci 6/101, Spring More on Python, Tools, Compsci 101 l APTs, Assignments, Tools  APT: Algorithmic Problem-solving and Testing  How to get.
Server - Client Communication Getting data from server.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
JSON COMPSCI 105 SS 2015 Principles of Computer Science.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Lecture 09 – Classes.  At the end of this lecture, students should be able to:  Define a new class  Store state information about instances of the.
AJAX. Ajax  $.get  $.post  $.getJSON  $.ajax  json and xml  Looping over data results, success and error callbacks.
Download class materials onto your desktop… as usual.
1. COMPUTERS AND PROGRAMS Rocky K. C. Chang September 6, 2015 (Adapted from John Zelle’s slides)
1 Essential Computing for Bioinformatics Bienvenido Vélez UPR Mayaguez Lecture 3 High-level Programming with Python Part III: Files and Directories Reference:
JSON. JSON as an XML Alternative JSON is a light-weight alternative to XML for data- interchange JSON = JavaScript Object Notation It’s really language.
JSON (Copied from and from Prof Da Silva) Week 12 Web site:
XML & JSON. Background XML and JSON are to standard, textual data formats for representing arbitrary data – XML stands for “eXtensible Markup Language”
Xi Wang Yang Zhang. 1. Strings 2. Text Files 3. Exceptions 4. Classes  Refer to basics 2.py for the example codes for this section.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Computer Science 112 Fundamentals of Programming II Data Fields for I/O and Message Boxes for Error Recovery.
Equality, references and mutability COMPSCI 105 SS 2015 Principles of Computer Science.
Storing Data.
Multimedia Summer Camp
Introduction to Programming
Fundamentals of Programming I Overview of Programming
COMPSCI 107 Computer Science Fundamentals
Topic: File Input/Output (I/O)
Lesson 10: Dictionaries Topic: Introduction to Programming, Zybook Ch 9, P4E Ch 9. Slides on website.
CSC201: Computer Programming
CompSci 6 Introduction to Computer Science
COMPSCI 107 Computer Science Fundamentals
JSON Crash Course Traversy Media.
Variables, Expressions, and IO
Statement atoms The 'atomic' components of a statement are: delimiters (indents, semicolons, etc.); keywords (built into the language); identifiers (names.
Functions CIS 40 – Introduction to Programming in Python
Introduction to Python
Topics Introduction to File Input and Output
Built in Fairfield County: Front End Developers Meetup
Week 8 Classes and Objects
JSON Data Demo.
Classes, Objects and lists
Strings and Serialization
Fundamentals of Python: First Programs
Lesson 10: Dictionaries Class Chat: Attendance: Participation
Topics Introduction to File Input and Output
Computer Programming-1 CSC 111
Topics Introduction to File Input and Output
Functions, Procedures, and Abstraction
Presentation transcript:

JSON COMPSCI 105 S Principles of Computer Science

Exercise  Exercise  Which of the following statements is true? a) If both except and finally blocks are defined, except block must precede the finally block. b) A try block is preceded by at least one finally block c) For each try block there must be at least one except block defined. d) A try block may be followed by any number of finally blocks Lecture 09COMPSCI 1052

Learning outcomes  At the end of this lecture, students should be able to:  understand what JSON is used for  recognise information in JSON format  use the Python JSON library to read and write standard Python data types  Resources:  Tutorials Point: JSON with Python   Python Documentation  COMPSCI 1053Lecture 09

Question?  Given a particular set of data, how do you store it permanently?  What do you store on disk?  What format?  Can you easily transmit over the web?  Will it be readable by other languages?  Can humans read the data?  Examples:  A square  A dictionary COMPSCI 1054Lecture 09 methods state num: den: 3 4

Storage using plain text  Advantages  Human readable (good for debugging / manual editing)  Portable to different platforms  Easy to transmit using web  Disadvantages  Takes more memory than necessary  Use a standardized system -- JSON  Makes the information more portable COMPSCI 1055Lecture 09

JavaScript Object Notation  JSON stands for JavaScript Object Notation, which is a lightweight format used for data interchange.  Text-based notation for sharing data  Human readable form  Object  Unordered set of name-value pairs  names must be strings  { name1 : value1, name2 : value2, …, nameN : valueN }  Array  Ordered list of values  [ value1, value2, … valueN ] COMPSCI 1056Lecture 09

Writing JSON using Python  json.dumps( data ) – converting into JSON format  Accepts Python object as an argument  Returns a string containing the information in JSON format  Typically write this string to a file  Remember to import the JSON module COMPSCI 1057 import json def write(data, filename): file = open(filename, 'w') str_out = json.dumps(data) file.write(str_out) file.close() import json def write(data, filename): file = open(filename, 'w') str_out = json.dumps(data) file.write(str_out) file.close() Lecture 09

Reading JSON using Python  json.loads( data ) – changing back to Python objects  Accepts string as an argument  The string should be in JSON format  Returns a Python object corresponding to the data COMPSCI 1058 def read(filename): file = open(filename) str_in = file.read() file.close() data = json.loads(str_in) return data def read(filename): file = open(filename) str_in = file.read() file.close() data = json.loads(str_in) return data Lecture 09 write('Hello World', 'hello.txt') print(read('hello.txt')) write('Hello World', 'hello.txt') print(read('hello.txt')) "Hello World" Double quotes ‘hello.txt’

Example 2: Writing a dictionary  Create a dictionary Lecture 09COMPSCI 1059 my_dict = {'Angela':'86620','adriana':'87113, 'ann':'84947'} file_name = 'test_dict.txt' write(my_dict, file_name) my_dict = {'Angela':'86620','adriana':'87113, 'ann':'84947'} file_name = 'test_dict.txt' write(my_dict, file_name) {"Angela": "86620", "Adriana": "87113", "Ann": "84947"} print(read(file_name)) def write(data, filename): file = open(filename, 'w') str_out = json.dumps(data) file.write(str_out) file.close() def write(data, filename): file = open(filename, 'w') str_out = json.dumps(data) file.write(str_out) file.close() Double quotes ‘test_dict.txt’ {'Angela': '86620', 'Ann': '84947', 'Adriana': '87113'} Single quotes def read(filename): file = open(filename) str_in = file.read() file.close() data = json.loads(str_in) return data def read(filename): file = open(filename) str_in = file.read() file.close() data = json.loads(str_in) return data

Writing JSON using pretty printing  json.dumps( data )  json.dumps( data, indent=4, sort_keys=True )  Formats the output over multiple lines COMPSCI {'b': ['HELLO', 'WORLD'], 'a': ['hello', 'world']} { "a": [ "hello", "world" ], "b": [ "HELLO", "WORLD" ] } { "a": [ "hello", "world" ], "b": [ "HELLO", "WORLD" ] } Lecture 09 Double quotes A dictionary

What about user-defined classes?  Point class  Can create a dictionary to store state information then use JSON COMPSCI class Point: def __init__(self, loc_x, loc_y): self.__x = loc_x self.__y = loc_y def __str__(self): return '(' + str(self.__x) + ',' + str(self.__y) + ')' class Point: def __init__(self, loc_x, loc_y): self.__x = loc_x self.__y = loc_y def __str__(self): return '(' + str(self.__x) + ',' + str(self.__y) + ')' p = Point(2, 3) my_dict = {'__class__': 'Point', 'x' : p.getX(), 'y' : p.getY()} p = Point(2, 3) my_dict = {'__class__': 'Point', 'x' : p.getX(), 'y' : p.getY()} Lecture 09 value of x value of y

What about user-defined classes?  Can use json to read and extract the state information  Example: COMPSCI file_name = 'test_point.txt' write(my_dict, file_name) file_name = 'test_point.txt' write(my_dict, file_name) Lecture 09 data = read(file_name) result = Point( data['x'], data['y'] ) print (result) data = read(file_name) result = Point( data['x'], data['y'] ) print (result) { "__class__": "Point", "x": 2, "y": 3 } { "__class__": "Point", "x": 2, "y": 3 } ‘tes_point.txt ’

Exercise  Given a Square class, write methods that dump and read JSON COMPSCI import json import io class Square: def __init__(self, len): self.__side = len def getSide(self): return self.__side def __repr__(self): return 'Square({0})'.format(self.__side) def __str__(self): return str(self.__side) + ' x ' + \ str(self.__side) + ' square' import json import io class Square: def __init__(self, len): self.__side = len def getSide(self): return self.__side def __repr__(self): return 'Square({0})'.format(self.__side) def __str__(self): return str(self.__side) + ' x ' + \ str(self.__side) + ' square' Lecture 09

Summary  JSON is a standard way to exchange data  Easily parsed by machines  Human readable form  JSON uses dictionaries and lists  Dictionaries are unordered  Lists are ordered  Symbols used in JSON are the same as Python  Double quotes used for strings COMPSCI 10514Lecture 09