Home >Backend Development >Python Tutorial >How to parse a JSON file

How to parse a JSON file

anonymity
anonymityOriginal
2019-05-25 14:08:414063browse

JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of ECMAScript. JSON uses a completely language-independent text format, but also uses conventions similar to the C language family (including C, C++, Java, JavaScript, Perl, Python, etc.). These properties make JSON an ideal data exchange language. It is easy for humans to read and write, and it is also easy for machines to parse and generate (generally used to increase network transmission rates).

JSON consists of list and dict respectively in python.

These are two modules used for serialization:

json: used to convert between strings and python data types pickle: used between python-specific types and python data types Convert

The Json module provides four functions: dumps, dump, loads, load

The pickle module provides four functions: dumps, dump, loads, load

How to parse a JSON file

json dumps converts the data type into a string dump converts the data type into a string and stores it in the file loads converts the string into a data type load opens the file and converts it from a string into a data type

Json can exchange data between different languages, while pickle can only be used between python. JSON can only serialize the most basic data types, and JSON can only serialize commonly used data types (lists, dictionaries, lists, strings, numbers, etc.), such as date formats and class objects! Josn can't do it. Pickle can serialize all data types, including classes and functions.

Example:

dumps: Convert dictionary in python 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))

loads: Convert string For dictionary

new_dict = json.loads(json_str)
print(new_dict)
print(type(new_dict))

dump: Write data into json file

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

load:Open the file and convert the string into 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)

The above is the detailed content of How to parse a JSON file. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn