Python and JSON data are converted to each other, repr and eval () use

Source: Internet
Author: User

Python Data Conversion JSON
Import JSON  # Imports JSON package data = [    {        "id": 1,        "username": "Zhangshan",        "password": "123qwe",        "lock ": True    },    {        " id ": 2,        " username ":" Lisi ",        " password ":" 123qwe ",        " lock ": true    },    {        "id": 3,        "username": "Wangwu",        "password": "123qwe",        "lock": False    }]jsonstr = Json.dumps (data) # JSON data print (JSONSTR) # python data print (' Raw data string: ', repr (JSONSTR))

  

Convert JSON to Pathon data
Pystr = Json.loads (jsonstr) print (PYSTR)
Repr and eval usage
Repr (object)  # Converts an object to a string, like Java's ToString () eval (str)  # Converts a repr () converted string into an object  
JSON Read and write
# Write JSON data with open (' Data1.json ', ' W ') as F:    json.dump (data, f) # Read data with open (' Data1.json ', ' R ') as F:    data = j Son.load (f)
Summarize:

Data conversion

First step: Introducing the JSON package: Import JSON

Step Two: Use Json.dumps (pythonobj) to convert Python data to JSON data

Step Three: Use Json.loads (jsonobj) to convert JSON data to Python data

File Write read

Write using Dump

Read with load

   

Python and JSON data are converted to each other, repr and eval () use

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.