tags:

views:

79

answers:

3

I use the built in json for python 2.6. I'm having tons of trouble parsing jsons like this:

{
 name: 'some name'
 value: 'some value'
}

I found two reasons -

  1. ' doesn't work. You need "
  2. the keys of the dictionary need to be strings. I.e "name"/"value"

Am I missing something? Is there a way to parse this kind of dictionary using the json package? Is there any other python package that can parse this?

Thanks

+3  A: 

I think that what you want is not a "stronger" parser but a broken parser that will parse broken code. See the standard

specifically,

  • The keys of an object are defined to be strings

  • Strings are defined to be "" or "chars" where chars has the pretty much obvious meaning

There's someplace on the internet where you can watch Douglass Crockford make semi-witty remarks about why this is the case. It has to do with compatibility with non-javascript languages though. Specifically, you could not have

{name :'some name', value: 'some value'} 

as a dict in python unless name and some value where preexisting, hashable variables;

Broken parsers in general are bad. Just look at the mess that broken HTML parsers in browsers have created where any idiot can make a web site. That dude that wrote all those RFC's had it wrong: It's better to be strict in what you emit and what you accept.

aaronasterling
Completely agree - just look at the mess created by non-compliant HTML being accepted by web browsers! Now you have to work ten times as hard to get one simple page display the same across browsers.
Arrieta
A: 

There are:

  • simplejson, which is "is the externally maintained development version of the json library included with Python 2.6 and Python 3.0, but maintains backwards compatibility with Python 2.5."
  • cjson

(Not sure if they'll parse broken JSON.)

Bruno
+2  A: 

The problem is not with the Python module, the problem is with your string, which could be whatever you say, but not JSON, so it cannot be parsed by a JSON parser.

If it were JSON it would look like:

{"name":"some name", "value":"some value"}

So, it is not a problem with the Python module. It is like asking for a "stronger python compiler" because C-Python cannot parse:

using json
json.loads(my_string)

Obviously the first line is simply not Python, so we cannot ask Python to interpret it.

Now if you want to parse that string I recommend that you either: make it a JSON string OR use Pyparsing for writing a quick and dirty parser (I guarantee it will work great in less than, say, 50 lines).

Cheers,

Juan.

Arrieta