0

here is the problem, I want to dump and load windows paths in python under a unix system:

a = {"c":"a\b"}
b = json.dumps(a)
json.loads(b)
{u'c': u'a\x08'}

So, where did I go wrong?

Kai
  • 376
  • 1
  • 4
  • 17
  • `\b` is not `\\b` which is the real `\b`. Use `r"a\b"` instead. Take a look at http://stackoverflow.com/questions/4780088/in-python-what-does-preceding-a-string-literal-with-r-mean – emesday Jun 22 '14 at 14:07

2 Answers2

0

You failed to remember that the backslash character in a string literal can introduce an escpae sequence. "\b" represents the one-character string containing only a backspace.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
0

The '\' us being used for escaping b here. You can use "a\\b" or r"a\b" to avoid this problem.

a = {"c":"a\\b"} # or a = {"c":r"a\b"}
b = json.dumps(a)
print json.loads(b)['c']

output

a\b
Ashoka Lella
  • 6,631
  • 1
  • 30
  • 39
  • Okay, but you use the print command to format it. What if I want to dump it to a file in the output format? Or hand it over to a function? Two things I need to do ... and thank you very much! – Kai Jun 23 '14 at 09:26
  • @Kai, you mean print `a` into a file. If you dump `a` as json, you can't avoid not printing `"a\\b"`. In other words if you print it in output format you can't reuse it as a json file. – Ashoka Lella Jun 23 '14 at 09:42
  • I understand. So, if I load it from the file and hand it to functions, which of course need the "a\b" format, I just have to format it? Or should I format the dictionary after loading, before I use it? – Kai Jun 23 '14 at 11:16
  • Say `a = {"c":"a\\b"}`. Now you dump it to a file. It gets written as `"a\\b"` and read as `"a\\b"`. But, its actually `"a\b"`. So, after reading it, if you try to print `a["c"]` it would print `a\b` – Ashoka Lella Jun 23 '14 at 11:43