SoFunction
Updated on 2025-03-03

C++ Example code for using yaml-cpp library to operate YAML

1. YAML Introduction Tutorial

Basic syntax

  • Case sensitivity
  • Use indentation to represent hierarchical relationships
  • Tabs are not allowed, only spaces are allowed
  • The number of indented spaces is not important, as long as the elements of the same level are left aligned
  • '#' means comment

Data Type

YAML supports the following data types:

  • Object: a collection of key-value pairs, also known as mapping/hash/dictionary
  • Array: a set of values ​​arranged in order, also known as sequence / list
  • Scalars: single, non-redividable value

YAML Objects

Object key-value pairs are represented using colon structurekey: value, add a space after the colon.

Can also be usedkey:{key1: value1, key2: value2, ...}

Indentation can also be used to represent hierarchical relationships;

key: 
    child-key: value
    child-key2: value2

For more complex object formats, you can use a question mark plus a space to represent a complex key, and use a colon plus a space to represent a value:

?  
    - complexkey1
    - complexkey2
:
    - complexvalue1
    - complexvalue2

It means that the attribute of the object is an array [complexkey1,complexkey2], and the corresponding value is also an array [complexvalue1,complexvalue2]

YAML array

Lines starting with - represent an array:

- A
- B
- C

YAML supports multi-dimensional arrays and can be represented in line:

key: [value1, value2, ...]

A child member of a data structure is an array, and you can indent a space under this item.

-
 - A
 - B
 - C

A relatively complex example:

companies:
    -
        id: 1
        name: company1
        price: 200W
    -
        id: 2
        name: company2
        price: 500W

It means that the companies attribute is an array, and each array element is composed of three attributes: id, name, and price.

Arrays can also be represented in a flow manner:

companies: [{id: 1,name: company1,price: 200W},{id: 2,name: company2,price: 500W}]

Composite structure

Arrays and objects can form composite structures, for example:

languages:
  - Ruby
  - Perl
  - Python 
websites:
  YAML:  
  Ruby:  
  Python:  
  Perl: 

Convert to json to:

{ 
  languages: [ 'Ruby', 'Perl', 'Python'],
  websites: {
    YAML: '',
    Ruby: '',
    Python: '',
    Perl: '' 
  } 
}

Pure quantity

Pure quantities are the most basic and non-redividable values, including:

  • String
  • Boolean value
  • Integer
  • Floating point number
  • Null
  • time
  • date

Use an example to quickly understand the basic use of pure quantities:

boolean: 
    - TRUE  #true, True    - FALSE  #false, False is OKfloat:
    - 3.14
    - 6.8523015e+5  #Scientific notation can be usedint:
    - 123
    - 0b1010_0111_0100_1010_1110    #Binary representationnull:
    nodeName: 'node'
    parent: ~  #Use ~ means nullstring:
    - Ha ha
    - 'Hello world'  #You can use double quotes or single quotes to wrap special characters    - newline
      newline2    #Stands can be split into multiple lines, each line will be converted into a spacedate:
    - 2018-02-17    #Date must use ISO 8601 format, i.e. yyyy-MM-dddatetime: 
    -  2018-02-17T15:02:31+08:00    #Time useISO 8601Format,Use between time and dateTconnect,Last used+Represents the time zone

Quote

& anchor and * alias, can be used to reference:

defaults: &defaults
  adapter:  postgres
  host:     localhost

development:
  database: myapp_development
  <<: *defaults

test:
  database: myapp_test
  <<: *defaults

Equivalent to:

defaults:
  adapter:  postgres
  host:     localhost

development:
  database: myapp_development
  adapter:  postgres
  host:     localhost

test:
  database: myapp_test
  adapter:  postgres
  host:     localhost

&Used to establish anchor points (defaults),<<Indicates merged into the current data,*Used to reference anchor points.

Here is another example:

- &showell Steve 
- Clark 
- Brian 
- Oren 
- *showell 

The code to convert to JavaScript is as follows:

[ 'Steve', 'Clark', 'Brian', 'Oren', 'Steve' ]

2. Install the yaml-cpp library

yaml-cpp is an open source library, on github:/jbeder/yaml-cpp. There are installation instructions on Github. Y users can choose to compile and install from source code, or use the package manager to install it.

1. Install from source:

mkdir build
cd build
cmake ..

The default yaml-cpp is a static library, which is the .a file under the unix class system. If you want to build a dynamic library, you need to specify it when cmake:

cmake ..  -D BUILD_SHARED_LIBS=ON

After the compilation is successful, the library file will be generated. You only need to copy the library file and header file to your own project and you can use it.

If you don't want to copy the header file to a different project every time, you can copy the header file to the system default directory. For example, the address of ubuntu is /usr/local/include, just copy the library file to the system's default lib file, for example, ubuntu is /usr/local/lib.

With header files and libraries, you can write code smoothly.

2. Use the APT command to install:

sudo apt install libyaml-cpp-dev

3. Generate YAML examples

1. Yaml file format

name: John
age: 25
hobbies:
  - reading
  - coding

++ Code

#include &lt;iostream&gt;
#include &lt;fstream&gt;
#include &lt;yaml-cpp/&gt;
 
// g++ -o yaml_example yaml_sample_gen.cpp -lyaml-cpp
 
int main() {
    // Create a YAML node    YAML::Node config;
    config["name"] = "John";
    config["age"] = 25;
    config["hobbies"].push_back("reading");
    config["hobbies"].push_back("coding");
 
    // Write to YAML file    std::ofstream fout("");
    fout &lt;&lt; config;
    ();
 
    return 0;
}

In the example above, we first create a YAML node and populate the data into the node. Then, we use<<Operator writes YAML nodes toin the file.

++Compile command

g++ -o yaml_example yaml_sample_gen.cpp -lyaml-cpp

Compile

cmake_minimum_required(VERSION 3.5)

# Project Nameproject(YamlExample)

# Setting C++ Standardset(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Find the yaml-cpp libraryfind_package(yaml-cpp REQUIRED)

# Contains yaml-cpp header fileinclude_directories(${YAML_CPP_INCLUDE_DIR})

# Add executable fileadd_executable(yaml_example )

# Link yaml-cpp librarytarget_link_libraries(yaml_example ${YAML_CPP_LIBRARIES})

The above is the detailed content of the sample code of C++ using the yaml-cpp library to operate YAML. For more information about C++ yaml-cpp operating YAML, please follow my other related articles!