Yaml the use of the Python tutorial in the detailed

Source: Internet
Author: User
Tags hash json to yaml stdin in python


Yaml is an easy to read, suitable for Presentation program language data structure, can be used to exchange data between different programs, support generic tools, support serial processing, rich expression capabilities and scalability, Easy-to-use language. Yaml use indentation or explicit indicatior (such as {}) to indicate nesting of properties, more intuitive and simple.

I. Format of the YAML

The format and characteristics of YAML are as follows:

Yaml using printable Unicode characters, you can use UTF-8 or UTF-16.
The structure is represented by using a blank character as a file indent, but you cannot use the tab.
Annotations start with a well font size (#) and can appear anywhere in a row, with only one row (that is, a commonly called single-line annotation)
Each manifest member is represented in a single line and starts with a short bar + white space (-). or use square brackets ([]) and separate members with commas + blanks (,).
The members of each hash table separate the key values and contents with a colon + white space (:). Or use curly braces ({}), separated by commas + blanks (,).
The key value of a hash table can be used with a question mark (?). The start, which is used to explicitly represent the key values of multiple words.
Strings usually do not use quotes, but you can use double quotes (") or single quotes (') when necessary.
When you use double quotes to denote a string, the caret (which is similar to the C language) can be used to represent a special character by using a backslash (\) that starts with a slash.
Blocks are delimited with indents and modifiers (not necessary) and other data, with new rows reserved (preserve) (using symbols | or new line folding (Flod) (using the symbol >) in two ways.
In a single file, multiple files can be distinguished from three consecutive hyphens (---).
In addition, there are three consecutive points of choice (...). Used to indicate the end of a file.
Duplicate content can be copied from the reference mark asterisk (*) to the Anchor point tag (&).
The specified format can use two exclamation marks (!!) followed by a name.
A single file in an archive can use instructions, using a percent sign (%). There are two instruction instructions defined in the YAML1.1 version:
%yaml instructions to identify the YAML version of the file.
%tag instructions are used to mark the beginning of a URI. This method is useful when marking the shape of a node.
Yaml you use commas and colons, you must follow a blank character.

Second, the use of Pyyaml

1, installation

Python install Pyyaml module can use Yaml, open Https://pypi.python.org/pypi/PyYAML Download, current version 3.11. The module is described in the PyPI site as follows: Pyyaml features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and Sensible error messages.

Hosts that can connect to the network can also be installed through the PIP install Pyyaml or Easy_install pyymal.

2, Yaml.load and Yaml.dump method

The module provides a number of methods, but the common methods are only two yaml.load and Yaml.dump, the following is a version-related YAML format file

[Root@361way yaml]# cat Tree.yaml

treeroot:

branch1: Name:node

1

branch1-1:

Name:node 1-1

branch2:

name:node 2

branch2-1:

name:node 2-1

Yaml.load Method:

# script Content

[Root@361way yaml]# cat load.py

import yaml

f = open (' Tree.yaml ')

Datamap = Yaml.load (f)

F.close ()

print Datamap

# Execution results are as follows

[Root@361way yaml]# python load.py {' Treeroot

': {' branch2 ': {' Branch2-1 ': {' name ': ' Node 2-1 '}, ' name ': ' Node 2 '}, ' Branch1 ': {' branch1-1 ': {' name ': ' Node 1-1 '}, ' name ': ' Node 1 '}}


Yuml.dump Method:

Here also takes the above script, calls inside the DATAMAP data, saves it to keep the new Yaml file, as follows:

# code as follows:
f = open (' Newtree.yaml ', "w")
Yaml.dump (Datamap, F)
F.close ()
#newtree. Yaml results are as follows
[ Root@361way yaml]# cat Newtree.yaml
treeroot: branch1:
branch1-1: {name:node 1-1}
name:node 1< c9/> branch2:
branch2-1: {name:node 2-1}
name:node 2


In addition, there are safe_load, Safe_dump, Load_all and other main methods, can be seen through Pydoc Yaml.

Iii. Yaml, XML and JSON
1, YAML and XML

The following is the same content, using the XML language tags and the Yaml language tags respectively:

# XML Tags two site

<site>

<name>sina</name>

<url>http://www.111cn.net </url >

</site>

<site>

<name>google</name>

<url>http://www.91it.org </url>

</site>

# Use YAML to mark two site

---

site:

name:sina

URL:HTTP://WWW.111CN . NET

---

site:

name:google

url:http://www.91it.org

# Use YAML to mark two site

---

sit E: {Name:sina, url:http://www.111cn.net}

---

site: {name:google, url:http://www.111cn.net}

From a read-view perspective, there is no advantage in Yaml relative to the XML language.

2, YAML and JSON

To be precise, JSON should be considered a word set under the YAML standard, and the Python statement can be used to translate between the two.

A, converting YAML to JSON

# python-c ' Import sys, YAML, JSON; Json.dump (Yaml.load (Sys.stdin), sys.stdout, indent=4) ' < File.yaml > File.json

or

#!/usr/bin/env python

Import Yaml,json

yml = "" "

---

foo:bar" "" "

data = Yaml.load (YML)

json = json.dumps (data)

Print (JSON)


B, convert JSON to YAML

# python-c ' Import sys, YAML, JSON; Yaml.dump (Json.load (Sys.stdin), sys.stdout, Default_flow_style=false) ' < File.json > File.yaml

or

#!/ usr/bin/env python

import json,yaml

str = ' {' foo ': ' Bar '} '

data = json.loads (str)

yml = Yaml.safe_d UMP (data)

print (YML)

Note: In many cases, you can even change the JSON suffix file directly to the Yaml suffix, using the Yaml language to parse directly.

Iv. the application of Yaml in Python language

The Yaml language is used in many excellent Python programs, such as the two automated work saltstack and ansible that the operational engineers often use. For more Pyyaml modules, you can also view their official wiki pages

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.