xml2json icon indicating copy to clipboard operation
xml2json copied to clipboard

[feature-request] json2xml

Open riccardolardi opened this issue 7 years ago • 3 comments

Could this also be used to parse JSON into XML?

riccardolardi avatar May 09 '17 11:05 riccardolardi

Hi

I am also in search of JSON to XML parse example, in StackOverflow they mentioned we can use this library to do so, (i mean JSON->XML). several level datatype(signed, unsligned, double ect..) identifications and work around needed in the parsing process. so its clear that c++ can't handle such process.

kindly if you have any inputs on this it would save my work.

TIA

shreyasck avatar Oct 23 '18 10:10 shreyasck

I'll pick up this thread when I get to the office. (It's the desk right next to this one. A two-meter commute!) I can provide guidance, but I can't provide code directly due to IP restrictions.

You'll need https://github.com/open-source-parsers/jsoncpp. This library and JsonCpp get along well.

jbmonroe avatar Nov 07 '18 13:11 jbmonroe

Okay, it goes a little something like this. Anything I don't detail explicitly I leave as an exercise in reading the JsonCpp documentation, but none of this is difficult. Writing it recursively removes most of the complexity.

  • Take the JSON output of this library and parse it with JsonCpp. You'll get a Json::Value.
  • You'll write std::string json2xml(Json::Value &val).
  • In that function, use Json::Value::getMemberNames() to get the top level names, and then walk the resulting vector.
  • In the loop, capture the member name and the value (val[name]).
  • Get the type of the value and act appropriately. You'll want some functions that generate XML tags, given the name and/or value of a tag. Those will likely be overloaded to account for all the possible value types. You'll need plain start and end tag functions to assist with the next bullet point.
  • When the returned type is either of Json::ValueType::arrayValue or Json::ValueType::objectValue, start a new tag with the correct name, call json2xml with the current value, and then follow with the appropriate end tag. In the case of an array you'll probably iterate that array and make recursive calls for each item.
  • If it hasn't been clear up to this point, you're catting the results of all the tag-function calls to a string returned by json2xml. (Use a stringstream or a plain string, that's up to you.)

jbmonroe avatar Nov 07 '18 14:11 jbmonroe