Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

could not parse string to Json object? Like string str=\"helloworld;E\\test\\log\\;end\" #297

Closed
daiziyi opened this issue Jan 11, 2017 · 2 comments

Comments

@daiziyi
Copy link

daiziyi commented Jan 11, 2017

hi, I want parse string to json object, but when the string has symbol "\", parsing is failure? why it happen? Here is my test code:

#include <json-c/json.h>
#include <string>
using namespace std;

int main()
{
    string str = "\"helloworld;E\\test\\log\\;end\""; /* not working! */
    //string str = "\"helloworld;E\test\log\;end\"";  /* work! */

    enum json_tokener_error jerr = json_tokener_success;

    json_object *json;

    json =  json_tokener_parse_verbose( str.c_str(), &jerr);

    if( jerr != json_tokener_success){
        cout << "Failed to parse string: ->" << str << "<- to json" << endl;
        cout << "ERROR: " << jerr << " " << json_tokener_error_desc(jerr) << endl;
        return -1;
    }

    cout << "json string: " << json_object_get_string(json) <<endl;

    json_object_put(json);
    return 0;

}

Console Result:

*******************************************************
1. when  str = "\"helloworld;E\\test\\log\\;end\""
output is: 
Failed to parse string: ->"helloworld;E\test\log\;end"<- to json
ERROR: 12 invalid string sequence
 
2. when  str = "\"helloworld;E\test\log\;end\""
output is: 
json string: helloworld;E	estlog;end
";E\\test\\log\\;" is invalid string sequence?    Thank you!
@ploxiln
Copy link
Contributor

ploxiln commented Jan 11, 2017

When you write \t in E\test in c or c++, that means a tab character. That's OK.

When you write \\ in test\\log in c or c++, that means a single actual \. Then, json sees \l in test\log and \l is an invalid escape sequence. See http://json.org/

@hawicz
Copy link
Member

hawicz commented Jan 15, 2017

If you actually want a backslash in the string object, you'll need another level of backslashes in your source code:

string str = "\"helloworld;E\\\\test\\\\log\\\\;end\""; /* not working! */

Turns into this sequence of bytes in memory:

  "helloworld;E\\test\\log\\;end"

which will then get parsed into this sequence of bytes by json-c:

  helloworld;E\test\log\;end

@hawicz hawicz closed this as completed Jan 15, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants