JSON 분석

Machine Learning 2019. 1. 18. 20:14 |
반응형

Python 기본 라이브러리 json을 이용해 JSON (JavaScript Object Notation) 형식을 분석할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import urllib.request as req
import os.path
import json
 
url = "https://api.github.com/repositories"
filename = "repositories.json"
 
if not os.path.exists(filename):
    #req.urlretrieve(url, filename)
    # Legacy interface. It might become deprecated at some point in the future.
    with req.urlopen(url) as contents:
        jsn = contents.read().decode("utf-8"# .decode("utf-8")이 없으면 jsn에는 str이 아닌 bytes가 저장 된다.
        # If the end of the file has been reached, read() will return an empty string ('').
        print(jsn)        
        # print(json.dumps(jsn, indent="\t")) 는 indent가 적용되어 출력되어야 하지만 원본이 indent가 적용되어 있지
        # 않아 indent 없이 출력 된다.
        with open(filename, mode="wt", encoding="utf-8") as f:
            f.write(jsn)
 
with open(filename, mode="rt", encoding="utf-8") as f:
    items = json.load(f) # JSON 문서를 갖고 있는 파일 포인터 전달. loads()는 JSON 형식의 문자열 전달
    for item in items:
        print("Name:", item["name"], "Login:", item["owner"]["login"])
 
test = {
    "Date" : "2019-01-17",
    "Time" : "21:30:24",
    "Location" : {
        "Town" : "Franklin",
        "City" : "Newyork",
        "Country" : "USA"
        }
    }
 
= json.dumps(test, indent="\t")
# Serialize obj to a JSON formatted str
# If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed
# with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects
# the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a
# string (such as "\t"), that string is used to indent each level.
print(s)
 
with open("dump.json", mode="wt") as f:
    json.dump(test, f, indent="\t")
# Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object)
cs


출력 결과 처음 부분.


출력 결과 마지막 부분.


write()으로 만든 repositories.json과 dump()으로 만든 dump.json 파일.



반응형
Posted by J-sean
: