Python - processing json files

1. Read the json file in [list] format: 
source file:

[     {             "Country Name": "Arab World",             "Country Code": "ARB",             "Year": "1960",             "Value": "96388069"     },     {             "Country Name": "Arab World",             "Country Code": "ARB",             "Year": "1961",             "Value": "98882541.4"     } ]
     
     
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

Code:

import json  # 将数据加载到一个列表中 filename = '123.json' with open(filename) as f:     pop_data = json.load(f)      # 打印每个国家2010年的人口数量     for pop_dict in pop_data:         country_name = pop_dict['Country Name']         population = pop_dict['Value']         print(country_name + ": " + population)
     
     
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12


2. Read a json file of type {dictionary}: 
source file:

{      "fontFamily": "微软雅黑",      "fontSize": 12,      "BaseSettings":{          "font":1,          "size":2                     } }
     
     
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Code:

# 设置以utf-8解码模式读取文件,encoding参数必须设置,否则默认以gbk模式读取文件,当文件中包含中文时,会报错 f = open("repositories.json", encoding='utf-8') setting = json.load(f)  # 注意多重结构的读取语法 family = setting['BaseSettings']['font'] style = setting['fontFamily']  print(family) print(style)
     
     
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10


3. Use of json module 
- json: used to convert between strings and python data types 
- Json module provides four functions: dumps, dump, loads, load

json dumps convert data type to string dump convert data type to string and store in file loads convert string to data type load open file convert from string to data type

(1). dumps: convert dictionary to string

import json  test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]} print(test_dict) print(type(test_dict))  #dumps 将数据转换成字符串 json_str = json.dumps(test_dict) print(json_str) print(type(json_str))
     
     
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

(2). Dump: Convert the dictionary to a string and write it to the json file

with open("../config/record.json","w") as f:     json.dump(json_str,f)     print("加载入文件完成...")
     
     
  • 1
  • 2
  • 3

(3). loads: converts the string to a dictionary

new_dict = json.loads(json_str) print(new_dict) print(type(new_dict))
     
     
  • 1
  • 2
  • 3

(4). load: open the file and convert the string to a data type

with open("../config/record.json",'r') as load_f:     load_dict = json.load(load_f)     print(load_dict)  load_dict['smallberg'] = [8200,{1:[['Python',81],['shirt',300]]}] print(load_dict)  with open("../config/record.json","w") as dump_f:     json.dump(load_dict,dump_f)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325257240&siteId=291194637