0

I am using JSONcpp library and facing problem to create json which contains / operator (like date : 02/12/2015). Below is my code:

JSONNODE *n = json_new(JSON_NODE);
json_push_back(n, json_new_a("String Node", "02/05/2015"));

json_char *jc = json_write_formatted(n);
printf("%s\n", jc);
json_free(jc);
json_delete(n);

Output :

{
    "String Node":"02\/05\/2015"
}

Check here "\/" in date, we want only "/" in date, so my expected output should look like this:

Expected output:

{
    "String Node":"02/05/2015"
}

How to get rid of it? We are using inbuilt library function and we can not modify library.

pkachhia
  • 1,876
  • 1
  • 19
  • 30

1 Answers1

0

According to this example

The json_new_a method will escape your string values when you go to write the final string.

The additional backslashes you are facing in the output are the result of adding escape characters. This is actually a good thing as it prevents both accidental and intentional errors.

I suppose the easies option for you would be to replace all \/ occurrences in output string with single /. I wrote a simple program to do so:

#include <iostream>
#include <string>
#include <boost/algorithm/string/replace.hpp>

using namespace std;

int main()
{
    //Here's the "json_char *jc" from your code
    const char* jc = "02\\/05\\/2015";

    //Replacing code
    string str(jc);
    boost::replace_all(str, "\\/", "/");

    //Show result
    cout << "Old output: " << jc << endl;
    cout << "New output: " << str << endl;
}

Live demo


BTW: libJSON is not really a C++ library - it's much more C-style which involves many low-level operations and is more complicated and obfuscated than more C++ish libraries. If you'd like to try, there is a nice list of C++ JSON libs here.

psliwa
  • 1,094
  • 5
  • 9
  • Thanks for your answer,but we did not use boost, we only use jsoncpp library and we are not passing string directly, we are using library inbuilt function – pkachhia Sep 03 '15 at 11:49
  • @pkachhia I see. Then, you could take advantage of something like these functions described here http://stackoverflow.com/questions/779875/what-is-the-function-to-replace-string-in-c . `json_char*` is basically pointer to `wchar_t` so it should work. – psliwa Sep 03 '15 at 11:57
  • @pkachhia Are you able to access the string before printing it? Does the code look exactly like in the example you provided? – psliwa Sep 03 '15 at 12:22
  • @PiotriSilwa we crosschecked buffer before passing to the library function json_write_formatted(), it looks exactly same (i.e. 02/05/2015). But when we print it after json_write_formatted() function it contains "\/" in output. – pkachhia Sep 04 '15 at 05:17