0

I am trying to parse a really simple json string in python but am getting a malformed string error. I know that it is a type string (see below), so this is not the problem Why does this string not work with ast.literal_eval

Why else might I get this error? How can I fix it?

g = "{\"RequestType\":\"1\" , \"FileName\":\"" + "test" + "\" }"
print type(g)  //prints string
d = ast.literal_eval(json.loads(g))  //throws malformed string error
Community
  • 1
  • 1
bernie2436
  • 22,841
  • 49
  • 151
  • 244
  • 3
    Also, save yourself the trouble of all the quoting and just use docstrings with formatting. E.g. `''' { "RequestType": "1" }'''` – Sanjay T. Sharma Nov 29 '13 at 07:51
  • Correct me if I'm wrong, but the link you included contains the following quote: "Concatenation using + isn't included within that: it's not a literal expression". Isn't that what you're doing in your declaration of the "g string" (huehuehue). You have a concatenation by +... that wouldn't fly if I'm reading it correctly. – Carlos Nov 29 '13 at 07:56
  • @mastashake57 but wouldn'y that concatenation happen once the g is created? Then the concatenation is done? – bernie2436 Nov 29 '13 at 07:57
  • When `g` is a string, `json.loads(g)` usually isn't. You're checking the type of the wrong thing. In general, when you have a problem like this, break your complex expression down into separate expressions, assign each value to a temporary variable, and then you can explore each of those temporary variables. Like: `obj = json.loads(g)`, then `d = ast.literal_eval(obj)`. Then you can see which of those two lines fails. And `print type(obj)` and see your problem. – abarnert Nov 29 '13 at 07:58
  • Oh, I see what you mean... good point then yes... I would presume that concatenation is done at that point. – Carlos Nov 29 '13 at 07:59
  • @abe3: Yes, the concatenation is evaluated in creating the `g` value, so `g` doesn't have any `+` character in it. (You can verify that with `print g`.) So mastashake57's comment is a red herring. – abarnert Nov 29 '13 at 08:01

1 Answers1

6

json.loads returns a dictionary, not a string. Presumably that's what you want, so you don't need literal_eval at all; just use json.loads(g) by itself. Or you could use ast.literal_eval(g) by itself. The point is you only need one of the functions, not both, since they do more or less the same thing.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384