010. json, json.loads(), json.dumps()
# @
# JSON is way which is used to express object in JavaScript
# Actually it's different between way of expressing object with JSON and way of expressing object with JavaScript
# Way of expressing object with JSON is similar to python's way
# @
# Data types which can be used in JSON are 6
# 1. numerics : 10, 12
# 1. string : "hello"
# 1. boolean : true, false
# 1. null : null
# 1. array : [10, "hello", true, null]
# 1. object :
# {
# "key1" : 10,
# "key2" : "hello",
# "key3" : true,
# "key4" : [12, "hello2"],
# "key5" :
# {
# "key6" : "hello3"
# }
# }
import json
import urllib.request as request
# @
# The most general form of JSON is array or object are located outter area
# because sending simple sing or number can be processed by ordinal data type without JSON
json_str = """[
{"name" : "apple", "price" : 1000},
{"name" : "banana", "price" : 2000},
{"name" : "pear", "price" : 3000},
{"name" : "orange", "price" : 4000},
{"name" : "prune", "price" : 5000}
]"""
# @
# If you want to convert external string into python data type,
# you can you json.load()
# you use json.load() when you load one value
# you use json.loads() when you load multiple values, which is used in most cases
# output is python data type
output = json.loads(json_str)
print(output)
print(type(output))
# # class 'list'
print('')
# If you want to convert python data type into external JSON string
# you can you json.dump() when you dump one value
# you can you json.dump() json.dumps() when you dump multiple values
# text is JSON data type
text = json.dumps(output)
print(text)
print(type(text))
# # class 'str'
# @
# go to api.github.com/repositories
jsonStrForGithub = request.urlopen("https://api.github.com/repositories").read()
outputOfGithub = json.loads(jsonStrForGithub)
print(outputOfGithub)
print(type(outputOfGithub))
# class 'list'
for item in output:
print(item["name"])
print(item["full_name"])
# login id of owner
print(item["owner"]["login"])
print()
# @
# It's also useful, when you scrap web data, to convert them into JSON string
# Then, you can use converted JSON string in various ways,
# so it's recommneded to also remember "json.dumps()"