Presentation is loading. Please wait.

Presentation is loading. Please wait.

JSON COMPSCI 105 S2 2015 Principles of Computer Science.

Similar presentations


Presentation on theme: "JSON COMPSCI 105 S2 2015 Principles of Computer Science."— Presentation transcript:

1 JSON COMPSCI 105 S2 2015 Principles of Computer Science

2 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

3 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  http://www.tutorialspoint.com/json/json_python_example.htm http://www.tutorialspoint.com/json/json_python_example.htm  Python Documentation  https://docs.python.org/3.3/library/json.html https://docs.python.org/3.3/library/json.html COMPSCI 1053Lecture 09

4 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

5 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

6 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

7 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

8 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’

9 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

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

11 What about user-defined classes?  Point class  Can create a dictionary to store state information then use JSON COMPSCI 10511 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

12 What about user-defined classes?  Can use json to read and extract the state information  Example: COMPSCI 10512 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 ’

13 Exercise  Given a Square class, write methods that dump and read JSON COMPSCI 10513 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

14 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


Download ppt "JSON COMPSCI 105 S2 2015 Principles of Computer Science."

Similar presentations


Ads by Google