解析并生成JSON [英] Parsing and generating JSON

查看:71
本文介绍了解析并生成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?

推荐答案

更新:如Pillsy的回答所述,JSON是自Mathematica 8开始用于Import和Export的内置格式:

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:

警告:这涉及执行eval(ToExpression),因此请勿使用此方法来解析来自不受信任来源的字符串.

首先,对于JSON解析,一个真正快速而又肮脏的部分解决方案是:

First, a really quick-and-dirty partial solution to JSON parsing would be this:

ToExpression[StringReplace[json, {"["->"{", "]"->"}", ":"->"->"}]]

即,只需将大括号替换为大括号,将冒号替换为箭头,然后进行评估. 剩下的就是在字符串内部进行那些替换. (还需要对null,true,false和科学表示法进行更多替换.)

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.)

对于非字符串内的问题,可能有一个更优雅的解决方案,但是首先想到的是进行"{"->"(*MAGICSTRING*){"之类的替换,然后进行评估(当字符串外的注释将消失时) ,逆转这些替换. (PS:稍后再讲,我对它的巧妙性感到非常满意,而且看起来非常强大.魔术弦乐FTW!)

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!)

说起来容易做起来难,但是以下JSON解析器似乎可以工作:

That's slightly easier said than done but the following JSON parser seems to work:

cat = StringJoin@@(ToString/@{##})&;          (* Like sprintf/strout in C/C++. *)
eval = ToExpression;            (* Mathematica function names are too verbose! *)

parseJSON[json_String] := With[{tr = {"["     -> "(*_MAGIC__[__*){",
                                      "]"     -> "(*_MAGIC__]__*)}",
                                      ":"     -> "(*_MAGIC__:__*)->",
                                      "true"  -> "(*_MAGIC__t__*)True",
                                      "false" -> "(*_MAGIC__f__*)False",
                                      "null"  -> "(*_MAGIC__n__*)Null",
                                      "e"     -> "(*_MAGIC__e__*)*10^",
                                      "E"     -> "(*_MAGIC__E__*)*10^"}},
  eval@StringReplace[cat@FullForm@eval[StringReplace[json, tr]], Reverse/@tr]]

(cateval是便捷函数.在这种情况下,简单地cat = ToString就可以工作,但我喜欢这个更通用的版本,它将其所有参数连接到一个字符串中.)

(cat and eval are convenience functions. Simply cat = ToString would work in this case but I like this more general version that concatenates all its arguments into a string.).

最后,这是一个生成JSON的函数(它确实需要更通用的cat,以及另一个用于以JSON合适的方式显示数字的实用程序函数):

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):

re = RegularExpression;
jnum[x_] := StringReplace[
  ToString@NumberForm[N@x, ExponentFunction->(Null&)], re@"\\.$"->""]

genJSON[a_ -> b_]  := genJSON[a] <> ":" <> genJSON[b]
genJSON[{x__Rule}] := "{" <> cat @@ Riffle[genJSON /@ {x}, ", "] <> "}"
genJSON[{x___}]    := "[" <> cat @@ Riffle[genJSON /@ {x}, ", "] <> "]"
genJSON[Null]      := "null"
genJSON[True]      := "true"
genJSON[False]     := "false"
genJSON[x_]        := jnum[x] /; NumberQ[x]
genJSON[x_]        := "\"" <> StringReplace[cat[x], "\""->"\\\""] <> "\""

这篇关于解析并生成JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆