0
  wstring  str1 = L"\"address\":\"test \ 00001\",\"type\":\"Float\""
  wstring  str2 = L"\"address\":\"test \\ 00001\",\"type\":\"Float\""
  wstring  str3 = L"\"address\":\"test \\\ 00001\",\"type\":\"Float\""
  wstring  str4 = L"\"address\":\"test \\\\ 00001\",\"type\":\"Float\""

JSON parsing fails in first three cases and returns address=test \\ 0001 type=Float But I want only one backslash in address, How to resolve this issue?

Austin
  • 29
  • 6
  • 1
    The c++ parser eats one layer of backslashes, and JSON expects to see a double backslash if you want the final parsed value to contain a single backslash. You can use raw C++ string literals to get rid of one level of escaping, if you want. – Botje Nov 18 '20 at 10:45
  • I'm already using L for wide characters string – Austin Nov 18 '20 at 11:15
  • No, that is something different still. See item 6 at [cpp reference](https://en.cppreference.com/w/cpp/language/string_literal) or [this SO question](https://stackoverflow.com/questions/56710024/what-is-a-raw-string) – Botje Nov 18 '20 at 11:35

1 Answers1

0

I every language you need to escape certain characters within a string literal. In C++ the escape sequence starts with a \ and followed by an escaped value for the char to be represented.

In str1 = "\"address\":\"test \ 00001\",\"type\":\"Float\"" the \ (the one before 00001) is \040 (040 is for the white space space) which is an unknown escape sequence so this escape sequence is ignore, and will result in:

"address":"test \ 00001","type":"Float"

For str2 = "\"address\":\"test \\ 00001\",\"type\":\"Float\"" the \\ is a vlaid escape sequnce for \ and that results in: "address":"test \ 00001","type":"Float"

For str3 = "\"address\":\"test \\\ 00001\",\"type\":\"Float\"" the \ (the one before 00001) is the same as in the first case. And \\ before it is valid. So it results in:

"address":"test \\ 00001","type":"Float"

For str4 = "\"address\":\"test \\\\ 00001\",\"type\":\"Float\"" the escape squeence is correct and resutls in:

"address":"test \\ 00001","type":"Float"

This string is then once again pares by the JSON parse, there \ is also used as beginning of the escape sequence, so after parsing this resulting "address":"test \\ 00001","type":"Float", you will get "test \ 00001" for address.

That's one of the reasons why you don't want to build a JSON representation of data manually.

t.niese
  • 39,256
  • 9
  • 74
  • 101