Skip to content

Instantly share code, notes, and snippets.

@luw2007
Created January 26, 2015 03:05
Show Gist options
  • Select an option

  • Save luw2007/ec016feb10357fdb59d9 to your computer and use it in GitHub Desktop.

Select an option

Save luw2007/ec016feb10357fdb59d9 to your computer and use it in GitHub Desktop.
python loads javascript sparse-array like [,0]

python中如何加载js中的稀疏数组

想要实现以下功能

>>> json.loads('[,0]')
[None, 0

原因

一直在linux 下用 translate-shell, 翻译中会附带上同义词. 但是win下没有好的支持. 找了一些类似调用google translate的实现. 但是都只是拿到翻译后的内容. 并不对同义词,反义词处理. 我猜想主要的原因是translate.google.com(国内可以访问.cn)返回的是js 的对象. 对比json会发现其中存在'[,,]'. 这是什么呢? 这就是js的稀疏数组.

解决

粗暴解决, 依靠hack simplejson的扫描器, 判断',,' 存在时返回一个None.

117a118,120
> if string[idx] == ',' and nextchar == ',':
> return None, idx
> print 'scan error [%s]' % string[idx]
133a137
> make_scanner = py_make_scanner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment