Python Read/Write Json File

python 33

Python and Java are two popular programming languages.
Today we will use This is dance as an example to write a small program to read and write Json files in Python.

JSON (JavaScript Object Notation) file is a lightweight, text-based editor that stores simple data structures and objects, and it is a standard data interchange format. It is primarily used for transmitting data between a web application and a server. 

Python Code:

import json
import codecs

def dance():
    mydict = {
    "show": "Street Dance of China 这就是街舞 ",
    "season": 3,
    "time": 2020,
    "Leaders": ["王一博 Yibo Wang", "张艺兴 Lay Zhang", "王嘉尔 Jackson Wang", "钟汉良 wa Zhong"],
    "Dance categories": [
        {"Category": "Old school", "Star": "亮亮 Spark hhl"},
        {"Category": "Locking", "Star": "韩宇 Han yu"},
        {"Category": "Wacking", "Star": "AC 小公主"},
        {"Category": "B-BOY", "Star": "蛇男 She nan"},
        {"Category": "Urban", "Star": "余衍林 Franklin Yu"},
        {"Category": "Jazz", "Star": "淡淡 Dan dan"}
    ]
}
    print(json.dumps((mydict), indent=2,  ensure_ascii=False))

    #save json files
    #    try:
    #    with open('data.json', 'w', encoding='utf-8') as fs:
    #        json.dump(mydict, fs)
    #except IOError as e:
    #    print(e)
    #print('Saved! ')
    
    #import json file
    #import requests
    #import json

#def main():
#    resp = requests.get('http://api.tianapi.com/guonei/?key=APIKey&num=10')
#    data_model = json.loads(resp.text)
#    for news in data_model['newslist']:
#        print(news['title'])

#main()  

dance()

Json Code:

{
  "show": "Street Dance of China 这就是街舞 ",
  "season": 3,
  "time": 2020,
  "Leaders": [
    "王一博 Yibo Wang",
    "张艺兴 Lay Zhang",
    "王嘉尔 Jackson Wang",
    "钟汉良 wa Zhong"
  ],
  "Dance categories": [
    {
      "Category": "Old school",
      "Star": "亮亮 Spark hhl"
    },
    {
      "Category": "Locking",
      "Star": "韩宇 Han yu"
    },
    {
      "Category": "Wacking",
      "Star": "AC 小公主"
    },
    {
      "Category": "B-BOY",
      "Star": "蛇男 She nan"
    },
    {
      "Category": "Urban",
      "Star": "余衍林 Franklin Yu"
    },
    {
      "Category": "Jazz",
      "Star": "淡淡 Dan dan"
    }
  ]
}

happy studying!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Social media & sharing icons powered by UltimatelySocial
%d bloggers like this: