13
$\begingroup$

Im looking for a efficient way of parsing JSON data in Mathematica. I am having a lot of problems with ImportString because it uses Java, is too slow, and uses too much memory (and, also, sometimes it just returns Null).

Do you know how to write a function for JSON parsing in Mathematica, or how to use any C/C++ (or other efficient) library from Mathematica?

$\endgroup$
2

2 Answers 2

9
$\begingroup$

Recent versions of Mathematica no longer use Java for parsing JSON, and work very fast.

There are at least three ways to read JSON.

  • Import[..., "JSON"] is fast an reliable. It returns nested Lists and Rules.

  • Import[..., "RawJSON"] is faster than "JSON" and returns nested Lists and Associations. These are much easier to work with than Rules.

  • The Developer` context has JSON reading and writing functions. There are functions for reading from files, streams or strings. There are functions for encoding/decoding Mathematica expressions (labelled Expression) and functions for reading/writing arbitrary JSON (labelled as Raw). These latter ones are essentially equivalent to Import[..., "RawJSON"].

    Example: Developer`ReadRawJSONString[str]

    These functions have much lower overhead than Import/Export because they do not have to invoke the entire import framework. In fact they are so fast that in some cases using them for data transfer with LibraryLink can be faster than using MathLink.

$\endgroup$
2
$\begingroup$

Longtime user, first time responder.

I am going to assume that by parsing you mean extracting values from JSON data and not transforming data into JSON.

There are a couple ways to parse JSON in Mathematica. Assuming the data is already a set of rules in Mathematica using Import[data, "JSON"] or something like that.

data = {blah -> blah, field1 -> var, field2 -> var2, blah-> blah, ...}

The first is Cases

Cases[data,{____ ,"field1"->var_, "field2"->var2_, ____}-> {var,var2}, Infinity]  

The second is replace.

dumvar = {"field1", "field2", ..} /. data 
$\endgroup$
1
  • $\begingroup$ By parsing, I mean converting a String (which is a JSON representation of some data) into a list that contains the data itself. $\endgroup$
    – José D.
    Commented Apr 21, 2014 at 20:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.