采集數(shù)據(jù)的時候經(jīng)常碰到一些JSON數(shù)據(jù)的Key值不是字符串,這些數(shù)據(jù)在JavaScript的上下文中是可以解析的,但在Python中,沒有該部分?jǐn)?shù)據(jù)的上下文,無法采用json.loads(JSON)
的形式導(dǎo)入。在網(wǎng)上搜集來一些方法以便日后使用。
def parse_js(expr): ''' 解析非標(biāo)準(zhǔn)JSON的Javascript字符串,等同于json.loads(JSON str) :param expr:非標(biāo)準(zhǔn)JSON的Javascript字符串 :return:Python字典 ''' obj = eval(expr, type('Dummy', (dict,), dict(__getitem__=lambda s, n: n))()) return obj
def parse_js(expr): ''' 解析非標(biāo)準(zhǔn)JSON的Javascript字符串,等同于json.loads(JSON str) :param expr:非標(biāo)準(zhǔn)JSON的Javascript字符串 :return:Python字典 ''' import ast m = ast.parse(expr) a = m.body[0] def parse(node): if isinstance(node, ast.Expr): return parse(node.value) elif isinstance(node, ast.Num): return node.n elif isinstance(node, ast.Str): return node.s elif isinstance(node, ast.Name): return node.id elif isinstance(node, ast.Dict): return dict(zip(map(parse, node.keys), map(parse, node.values))) elif isinstance(node, ast.List): return map(parse, node.elts) else: raise NotImplementedError(node.__class__) return parse(a)