-1

I have the following line:

BL: {version: 2, revision: 1}

I want to parse it, so that I will get in one variable BL, and on the other, I will get

[[version, revision], [2,1]]

I have the following code:

for line in file:
        print line.split(':',1)[0]; gives me the first word (BL)
        print line.split(': ',1)[1]
        data = json.loads(json.dumps(line.split(': ',1)[1]));

The problem is that data is not contained the data as variable, so when I do data[0], I get the char: {

What the correct way to do that?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Or Smith
  • 3,556
  • 13
  • 42
  • 69
  • 5
    You are trying to *dump the string to JSON*. That won't get what you want. You cannot use `json.loads()` either, because after splitting the string is still not valid JSON. – Martijn Pieters Jan 21 '15 at 14:33
  • You can test whether this is valid JSON without using a Python interpreter at all. For instance, you'll see that `jq . <<<'{version: 2, revision: 1}'` also fails. So **of course** `json.load()` won't work with something that isn't JSON. – Charles Duffy Jan 21 '15 at 17:13

1 Answers1

0

Your JSON is not valid since it's keys are not valid (you probably want strings there).

To get around it you could do something hacky like:

# give value to non-string keys, to use in eval
version = "version"
revision = "revision"
d = eval(line.split(": ", 1)[1])

print [d.keys(), d.values()]

This requires you to know all keys in advance.

I recommend you fix your input-generating script instead.

I always avoid eval.

Community
  • 1
  • 1
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88