Json

27798 ワード

json=dictionary
json配列=list
json文字列はloadという関数でPythonオブジェクトとして使用できます.


import json

json_str = """
[
    {"name":"홍길동","age":"32"},
    {"name":"임꺽정","age":"43"}
]
"""

json_obj = json.loads(json_str)
print(type(json_obj), json_obj)
print(type(json_obj[0]), json_obj[0])
print(type(json_obj[1]), json_obj[1])
print(json_obj[0:2])
import json

json_str = """
[
    {"name":"홍길동","age":"32"},
    {"name":"임꺽정","age":"43"}
]
"""

json_obj = json.loads(json_str)

for person in json_obj:
    print(person["name"] + "," + person["age"])

naver apiを使用して検索結果をインポートする
import os
import sys
import urllib.request
client_id = "_DAnhadrIPU0qOHagokk"
client_secret = "Z7chYt24Fv"

while True:
    input_str = input("검색할 단어 입력 : ")
    if input_str == "<exit>":
        break
    encText = urllib.parse.quote(input_str)
    url = "https://openapi.naver.com/v1/search/blog?query=" + encText # json 결과
    # url = "https://openapi.naver.com/v1/search/blog.xml?query=" + encText # xml 결과
    request = urllib.request.Request(url)
    request.add_header("X-Naver-Client-Id",client_id)
    request.add_header("X-Naver-Client-Secret",client_secret)
    response = urllib.request.urlopen(request)
    rescode = response.getcode()
    if(rescode==200):
        response_body = response.read()
        print(response_body.decode('utf-8'))
        print("=" * 60, end="\n\n\n")
    else:
        print("Error Code:" + rescode)
import requests
import json
import urllib

url = "https://openapi.naver.com/v1/search/blog?query="
client_id = "UmSKNm6SuI1UzNPGPQ39"
client_secret = "oLW4bNKt9F"

while True:
    input_str = input("검색할 단어 입력 : ")
    if input_str == "<exit>":
        break
    encText = urllib.parse.quote(input_str)
    url += encText
    result = requests.get(urllib.parse.urlparse(url).geturl(),
                      headers={"X-Naver-Client-Id":client_id,
                               "X-Naver-Client-Secret":client_secret})
    result_obj = result.json()
    print(result_obj)
    print("=" * 70, end="\n\n\n")
印刷すると結果がわかりにくいです.
このときデバッグすると簡単に見えます.

あるいはjsonツリーを使用することもできます.


ディスプレイを100に渡すとき.
while True:
    input_str = input("검색할 단어 입력 : ")
    if input_str == "<exit>":
        break
    encText = urllib.parse.quote(input_str)
    url += encText
    # 100개까지 보여주도록
    url += "&display=100"
    result = requests.get(urllib.parse.urlparse(url).geturl(),
                      headers={"X-Naver-Client-Id":client_id,
                               "X-Naver-Client-Secret":client_secret})
    result_obj = result.json()
    print(result_obj)
    print("=" * 70, end="\n\n\n")

json.dumps():オブジェクトを文字列に置換
import requests
import json
import urllib
import time

url = "https://openapi.naver.com/v1/search/blog?query="
client_id = "UmSKNm6SuI1UzNPGPQ39"
client_secret = "oLW4bNKt9F"

while True:
    input_str = input("검색할 단어 입력 : ")
    if input_str == "<exit>":
        break
    search_li = []
    for i in range(1, 201, 100):
        encText = urllib.parse.quote(input_str)
        url += encText
        url += "&display=100"
        url += "&start=" + str(i)
        print(url)
        result = requests.get(urllib.parse.urlparse(url).geturl(),
                          headers={"X-Naver-Client-Id":client_id,
                                   "X-Naver-Client-Secret":client_secret})
        result_obj = result.json()
        result_str = json.dumps(result_obj)
        print(type(result_str), result_str)
        search_li.append(result_obj)
        print("{} ~ {} 네이버 검색 수집".format(i, i+100))
        time.sleep(0.5)

    print(search_li)

# Google에 json tree
#          online json viewer

ファイルの保存
import requests
import json
import urllib
import time

url = "https://openapi.naver.com/v1/search/blog?query="
client_id = "UmSKNm6SuI1UzNPGPQ39"
client_secret = "oLW4bNKt9F"

def save_csv(json_obj):
    """,구분자로 가공해서 엑셀에서 볼 수 있도록 한다"""
    item_li = json_obj["items"]
    fp = open("naver_search.csv", "w", encoding="utf-8")
     #문서에 제목을 쓰기 위해 tilte, link, description과 같은 key 값을 뽑아낸다.
    column_li = item_li[0].keys()
    for column in column_li:
        fp.write(column)
        fp.write(",")
    fp.write("\n")
    for item in item_li:
        for column in column_li:
            fp.write(item[column].replace("<b>", "")
                                 .replace("</b>", "")
                                 .replace(",", " ")
                                 .strip())
            fp.write(",")
        fp.write("\n")

    fp.close()

def save_json(json_obj):
    """json문자열로 저장한 파일을 json.loads함수로 json object로 복원할 수 있다"""
    json_str = json.dumps(json_obj)
    with open("naver_search.json", "w", encoding="utf-8") as f:
        f.write(json_str)

input_str = input("검색할 단어 입력 : ")
encText = urllib.parse.quote(input_str)
url += encText
url += "&display=100"
print(url)
result = requests.get(urllib.parse.urlparse(url).geturl(),
                  headers={"X-Naver-Client-Id":client_id,
                           "X-Naver-Client-Secret":client_secret})
result_obj = result.json()
print(result_obj)

save_json(result_obj)
save_csv(result_obj)

# Google에 json tree
#          online json viewer