As others have pointed out, the issue is the non-standard trailing comma at the end of the list elements of the json string.
You can use ast.literal_eval()
in the example.
However, if you need to write your own json parser to deal with json that the Python library parser does not handle, you can use PyParsing to do so.
An example JSON parser, written in PyParsing, can easily be adapted to handle json with optional trailing commas:
testdata='''\
{
"key A":[
["some val", "value a1"],
["some val", "value a2"],
["some val", "value an"],
], "key B":[
["some val", "value b1"],
["some val", "value b2"]
],
"key X":[
["some val", "value x1"],
["some val", "value x2"]
]
}'''
json_bnf = """
object
{ members }
{}
members
string : value
members , string : value
array
[ elements ]
[]
elements
value
elements , value
value
string
number
object
array
true
false
null
"""
from pyparsing import *
import ast
def make_keyword(kwd_str, kwd_value):
return Keyword(kwd_str).setParseAction(replaceWith(kwd_value))
TRUE = make_keyword("true", True)
FALSE = make_keyword("false", False)
NULL = make_keyword("null", None)
LBRACK, RBRACK, LBRACE, RBRACE, COLON = map(Suppress, "[]{}:")
jsonString = dblQuotedString().setParseAction(removeQuotes)
jsonNumber = pyparsing_common.number()
jsonObject = Forward()
jsonValue = Forward()
jsonElements = delimitedList( jsonValue )
jsonArray = Group(LBRACK + Optional(jsonElements, []) + Optional(Suppress(",")) + RBRACK)
jsonValue << (jsonString | jsonNumber | Group(jsonObject) | jsonArray | TRUE | FALSE | NULL)
memberDef = Group(jsonString + COLON + jsonValue)
jsonMembers = delimitedList(memberDef)
jsonObject << Dict(LBRACE + Optional(jsonMembers) + RBRACE)
jsonComment = cppStyleComment
jsonObject.ignore(jsonComment)
And the result is the same as ast parsing it:
>>> dict(results.asList())==ast.literal_eval(testdata)
True
The advantage of 'rolling your own' in this case is to have control of what non-standard elements you have and how you want to handle them.
(Thanks to Paul McGuire for the PyParsing module and the json parser...)