解析并生成 JSON
Mathematica 的内置格式列表相当广泛;然而,JSON 并不在该列表中。 Mathematica 中是否有用于生成和解析 JSON 的现有解决方案,或者我们是否必须推出自己的解决方案?
Mathematica's list of built-in formats is pretty extensive; however, JSON is not on that list. Is there an existing solution for generating and parsing JSON in Mathematica, or are we going to have to roll our own solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更新:正如 Pillsy 的回答所述,JSON 是 Mathematica 8 中导入和导出的内置格式: http://reference.wolfram.com/mathematica/ref/format/JSON.html。但是,正如评论中所讨论的,从 Mathematica 10.4.1 开始,以下似乎是更强大的解决方案:
警告:这涉及执行 eval (ToExpression),因此不要使用它来解析来自不受信任来源的字符串。
首先,JSON 解析的一个真正快速而肮脏的部分解决方案是这样的:
即,只需将方括号替换为大括号,将冒号替换为箭头,然后对其进行评估。
剩下的就是不在字符串内部进行这些替换。
(还需要对 null、true、false 和科学记数法进行更多替换。)对于
不在字符串内的问题,可能有一个更优雅的解决方案,但首先想到的是进行像
这样的替换"{"->"(*MAGICSTRING*){"
然后,在 eval 之后(当字符串之外的注释消失时),反转这些替换。(PS:稍后再回到这个问题,我实际上对它的巧妙之处感到非常满意,而且它似乎非常强大。神奇的字符串 FTW!)
这说起来容易做起来难,但下面的 JSON 解析器似乎可以工作
:(
cat
和eval
是方便的函数,在这种情况下,简单的cat = ToString
就可以工作,但我喜欢这个更通用的版本,它将所有参数连接到其中。一个字符串。)。最后,这是一个生成 JSON 的函数(它确实需要更通用的
cat
,以及另一个用于以适合 JSON 的方式显示数字的实用函数):UPDATE: As noted in Pillsy's answer, JSON is a built-in format for Import and Export as of Mathematica 8: http://reference.wolfram.com/mathematica/ref/format/JSON.html. But, as discussed in the comments, the following seems to be a more robust solution as of Mathematica 10.4.1:
WARNING: This involves doing an eval (ToExpression) so don't use this to parse strings from untrusted sources.
First, a really quick-and-dirty partial solution to JSON parsing would be this:
Ie, just replace square brackets with curly braces and colons with arrows and then eval it.
All that remains is to not do those substitutions inside of strings.
(Also need a few more substitutions for null, true, false, and scientific notation.)
There's probably a more elegant solution to the not-within-strings problem, but the first thing to come to mind is to do substitutions like
"{"->"(*MAGICSTRING*){"
and then, after the eval (when comments outside of strings will have disappeared), reverse those substitutions.(PS: Coming back to this later, I'm actually pretty pleased with the cleverness of that, and it seems to be perfectly robust. Magic strings FTW!)
That's slightly easier said than done but the following JSON parser seems to work:
(
cat
andeval
are convenience functions. Simplycat = ToString
would work in this case but I like this more general version that concatenates all its arguments into a string.).Finally, here's a function to generate JSON (which does need the more general
cat
, as well as another utility function for displaying numbers in a JSON-appropriate way):从 Mathematica 8 开始,JSON 是一种内置格式,支持导入和出口。
As of Mathematica 8, JSON is a built-in format supporting both Import and Export.
这家伙有一个巧妙的解析示例Mathmatica 中的 JSON 代码
This guy has a clever example of parsing JSON code in Mathmatica