JSON

Method

  • json.dumps()
  • json.loads()
import json

person = {
    'id' : 1,
    'name' : 'MashCannu',
    'age' : 49,
}

output = json.dumps(person)
print(output)

dict_output = json.loads(output)
print(dict_output)
{"id": 1, "name": "MashCannu", "age": 49}
{'id': 1, 'name': 'MashCannu', 'age': 49}

Requests

jsonデータを取得する

  • requests.get(https://httpbin.org/json)
    • requests.post
      import json
      import requests
      
      r = requests.get("http://httpbin.org/json")
      
      // json形式をそのまま表示
      print(r.text)
      {
        "slideshow": {
          "author": "Yours Truly", 
          "date": "date of publication", 
          "slides": [
            {
              "title": "Wake up to WonderWidgets!", 
              "type": "all"
            }, 
            {
              "items": [
                "Why <em>WonderWidgets</em> are great", 
                "Who <em>buys</em> WonderWidgets"
              ], 
              "title": "Overview", 
              "type": "all"
            }
          ], 
          "title": "Sample Slide Show"
        }
      }
      import json
      import requests
      from pprint import pprint
      
      r = requests.get("http://httpbin.org/json")
      get_json = r.text
      
      dict_json = json.loads(get_json)
      
      pprint(dict_json["slideshow"]["slides"])
      pprint("-" * 60)
      pprint(dict_json)
      [{'title': 'Wake up to WonderWidgets!', 'type': 'all'},
       {'items': ['Why <em>WonderWidgets</em> are great',
                  'Who <em>buys</em> WonderWidgets'],
        'title': 'Overview',
        'type': 'all'}]
      '------------------------------------------------------------'
      {'slideshow': {'author': 'Yours Truly',
                     'date': 'date of publication',
                     'slides': [{'title': 'Wake up to WonderWidgets!', 'type': 'all'},
                                {'items': ['Why <em>WonderWidgets</em> are great',
                                           'Who <em>buys</em> WonderWidgets'],
                                 'title': 'Overview',
                                 'type': 'all'}],
                     'title': 'Sample Slide Show'}}