How to Use MongoDB's built-in JSON library to reverse sequence JSON strings

Source: Internet
Author: User
Requirements:

When parsing the field value in MongoDB, it is found that the value is a JSON string and needs to be deserialized.

Solution:

First, I thought about finding the corresponding CIDR library at http://www.json.org/json-zh.html. I tried jsoncppand JSON spirit, because it was built with scons, installed it, and could not play after compilation, and gave up. Try JSON spirit, (http://www.codeproject.com/Articles/20027/JSON-Spirit-A-C-JSON-Parser-Generator-Implemented), this stuff is good, it seems to be dependent on boost spirit, this I also installed, the installation process is still full of convenient, because all my c ++ projects use cmake, this is also used, so there is no problem in compilation and installation. The following is an example:

#include <json_spirit.h>const std::string test ="{""    \"text\": \"Home-plate umpire Crawford gets stung http://tinyurl.com/27ujc86\",""    \"favorited\": false,""    \"source\": \"<a href=\\\"http://apiwiki.twitter.com/\\\" rel=\\\"nofollow\\\">API</a>\",""    \"user\": {""        \"name\": \"Johnathan Thomas\"""    }""}";int main() {    namespace js = json_spirit;    js::mValue top;    js::read(std::string(test), top);    json_spirit::mObject obj = top.get_obj();    std::cout << "--------" << std::endl;        std::cout       << obj["text"     ].get_str()  << "\n"      << obj["favorited"].get_bool() << "\n"      << obj["source"   ].get_str()  << "\n"      << obj["user"     ].get_obj()["name"].get_str() << "\n";}

The following figure shows that MongoDB has its own bson structure, which is similar to JSON. JSON is found in the MongoDB source code package. h. This file shows that the fromjson method can be used. Haha
The following is my test code, because array is used in my value. Here we also use another method to convert bsonobj to array <bsonobj>.

#include <db/json.h>   // load fromjson method#include <iostream>#include <string>const std::string test =    "{ \"specs\" : "    " [ {\"id\":\"value1\" , \"name\":\"jack\"},"    "   {\"id\": \"value2\", \"name\":\"jack2\"},"    "{\"id\": \"value3\", \"name\":\"jack3\"}"    " ]"    "}";int main(){    try{        // { "specs" :  [ {"id":"value1" , "name":"jack"},   {"id": "value2", "name":"jack2"},{"id": "value3", "name":"jack3"} ]}        std::cout << "Test json string:" << test << std::endl;        // parse json method from json.h file        // throws MsgAssertionException if parsing fails.  The message included with        // this assertion includes a rough indication of where parsing failed.        mongo::BSONObj obj = mongo::fromjson(test);        mongo::BSONObj eles = obj["specs"].Obj();   // get array obj        /** add all values of the object to the specified vector.  If type mismatches, exception.            this is most useful when the BSONObj is an array, but can be used with non-arrays too in theory.            example:              bo sub = y["subobj"].Obj();              vector<int> myints;              sub.Vals(myints);        */        vector<mongo::BSONObj> specs;        eles.Vals(specs);        // print values        for(int i = 0; i < 3; ++i)            std::cout << specs.at(i)["id"].String() << ":" <<  specs.at(i)["name"].String()<< endl;    }    catch(const mongo::MsgAssertionException& e)    {        std::cout << "parse exception " << e.what() << endl;    }}

Running result:

gxl@gxl-desktop:~/Test_place$ g++ sample.cpp -o sample -I/usr/local/include/mongo/ -lmongoclientgxl@gxl-desktop:~/Test_place$ ./sample Test json string:{ "specs" :  [ {"id":"value1" , "name":"jack"},   {"id": "value2", "name":"jack2"},{"id": "value3", "name":"jack3"} ]}value1:jackvalue2:jack2value3:jack3

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.