Boost parsing JSON-formatted text

Source: Internet
Author: User

boost parsing JSON-formatted text


Flyfish 2015-4-1


Property_tree can parse text in Ini,xml,json,info and other formats

The following example is parsing text in JSON format


header files that need to be included

#include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp>const std:: String file_path= "C:\\Test.txt";



Generate Data
void Generate_user () {boost::p Roperty_tree::p tree root; Boost::p roperty_tree::p tree items;boost::p roperty_tree:: Ptree item1;item1.put ("ID", "1"); Item1.put ("Name", "Wang"); Items.push_back (Std::make_pair ("1", item1)); Boost:: Property_tree::p tree item2;item2.put ("ID", "2"), Item2.put ("Name", "Zhang"), Items.push_back (Std::make_pair ("2", ITEM2); boost::p roperty_tree::p tree item3;item3.put ("ID", "3") Item3.put ("Name", "Li"); Items.push_back (Std::make_ Pair ("3", Item3)), Root.put_child ("user", items), boost::p Roperty_tree::write_json (file_path,root);}




Reading data
void Read_user () {boost::p roperty_tree::p tree root;boost::p roperty_tree::p tree items;boost::p roperty_tree::read_ Json<boost::p roperty_tree::p tree> (File_path,root); Items=root.get_child ("user"); for (boost::p roperty_tree: :p tree::iterator It=items.begin (); It!=items.end () ++it) {//Traverse read Data string Key=it->first;//key idstring ID=it-> Second.get<string> ("ID"); string name=it->second.get<string> ("Name");}}



The data in the file
{"    user": {"1": {"        id": "1", "name": "Wang"},        "2": {"id": "2", "Name": "Zhang"},        "3": {"id": "3", "name": "Li"}}}    



Boost parsing JSON-formatted text

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.