用Python将JavaScript数组转为JSON
我正在从一个远程网站获取一个 .js 文件,这个文件里面有我想用 Google App Engine 上的 simplejson 库处理的数据。这个 .js 文件的内容大概是这样的:
var txns = [
{ apples: '100', oranges: '20', type: 'SELL'},
{ apples: '200', oranges: '10', type: 'BUY'}]
我对这个文件的格式没有控制权。最开始我只是想快速解决这个问题,所以我把字符串中的 "var txns = "
这一部分给去掉了,然后对这个字符串进行了多次 .replace(old, new, [count])
操作,直到它看起来像标准的 JSON 格式:
cleanJSON = malformedJSON.replace("'", '"').replace('apples:', '"apples":').replace('oranges:', '"oranges":').replace('type:', '"type":').replace('{', '{"transaction":{').replace('}', '}}')
现在它看起来是这样的:
[{ "transaction" : { "apples": "100", "oranges": "20", "type": "SELL"} },
{ "transaction" : { "apples": "200", "oranges": "10", "type": "BUY"} }]
你会怎么处理这个格式问题呢?有没有什么已知的方法(库或者脚本)可以把 JavaScript 数组格式化成 JSON 表示呢?
4 个回答
0
你可以创建一个中间页面,里面放一个JavaScript脚本,这个脚本的作用就是加载远程的数据,然后把它转换成JSON格式。接着,Python可以向这个中间页面发送请求,从中获取到格式良好的JSON数据。
4
我会使用yaml解析器,因为它在很多方面都更好。它是GAE自带的,也用于配置文件。Json其实是yaml的一部分。
你只需要去掉“var txns =”这部分,然后yaml就能处理剩下的事情。
import yaml
string = """[{ apples: '100', oranges: '20', type: 'SELL'},
{ apples: '200', oranges: '10', type: 'BUY'}]"""
list = yaml.load(string)
print list
这样你就得到了。
[{'type': 'SELL', 'apples': '100', 'oranges': '20'},
{'type': 'BUY', 'apples': '200', 'oranges': '10'}]
一旦加载完成,你随时可以把它再转回json格式。
5
用PyParsing写一个简单的解析器其实并不难。
import json
from pyparsing import *
data = """var txns = [
{ apples: '100', oranges: '20', type: 'SELL'},
{ apples: '200', oranges: '10', type: 'BUY'}]"""
def js_grammar():
key = Word(alphas).setResultsName("key")
value = QuotedString("'").setResultsName("value")
pair = Group(key + Literal(":").suppress() + value)
object_ = nestedExpr("{", "}", delimitedList(pair, ","))
array = nestedExpr("[", "]", delimitedList(object_, ","))
return array + StringEnd()
JS_GRAMMAR = js_grammar()
def parse(js):
return JS_GRAMMAR.parseString(js[len("var txns = "):])[0]
def to_dict(object_):
return dict((p.key, p.value) for p in object_)
result = [
{"transaction": to_dict(object_)}
for object_ in parse(data)]
print json.dumps(result)
这段代码会打印出
[{"transaction": {"type": "SELL", "apples": "100", "oranges": "20"}},
{"transaction": {"type": "BUY", "apples": "200", "oranges": "10"}}]
你也可以把赋值操作直接加到语法里。因为市面上已经有现成的解析器可以用,建议你还是使用那些更好。