How to interpret and extract the information from the JSON (JavaScript Object Notation)? I would extract the information and plot the information graphically. Please advise and comment. Thank you.

json = Import["http://www.google.com/finance/option_chain?q=AAPL&output=json"];
  • $\begingroup$ Use ImportString on the stuff you import and you should get a list of Mathematica rules or associations $\endgroup$ Mar 12 '16 at 0:56
  • $\begingroup$ the JSON is invalid. This is causing Mathematica to have a brain freeze. It also sent several online readers/converters I tried into a meltdown. $\endgroup$ Mar 12 '16 at 4:28
  • 4
    $\begingroup$ I'm voting to close this question as off-topic because the problem is that the JSON source is not valid $\endgroup$ Mar 12 '16 at 4:29

If we import the data as text, we can see that it is not valid JSON:

json = Import["http://www.google.com/finance/option_chain?q=AAPL&output=json", "Text"];

json // Short
(* {expiry:{y:2016,m:3,d:11},expirations... g_id:"22144",underlying_price:102.26} *)

The keys are not quoted despite the requirement of the JSON standard. This is a well-known problem with this API which, incidentally, Google officially withdrew years ago.

We can use string replacement to add the missing quotes and then import the result as JSON:

StringReplace[json, k:(LetterCharacter|"_")..~~":" :> "\""~~k~~"\":"] //
ImportString[#, "RawJSON"]&

   "puts"->{<|"cid"->"977422322110220","name"->"","s"->"AAPL160311P00055000","e"->"OPRA","p"->"-","c"->"-","b"->"-","a"->"0.05","oi"->"0","vol"->"-","strike"->"55.00","expiry"->"Mar 11, 2016"|>,...},
   "calls"->{<|"cid"->"340665151178585","name"->"","s"->"AAPL160311C00055000","e"->"OPRA","p"->"-","c"->"-","b"->"47.05","a"->"47.35","oi"->"0","vol"->"-","strike"->"55.00","expiry"->"Mar 11, 2016"|>,...},

The exhibited string replacement expression is very simplistic and in general might (or might not) need to be extended to handle whitespace before the colons or colons embedded within quoted string. Also, "RawJSON" format does not exist in Mathematica versions prior to 10.2 (use "JSON" instead).

  • $\begingroup$ May I ask a question, how to convert JSON data into datasets or tables? $\endgroup$ Mar 13 '16 at 2:08
  • 1
    $\begingroup$ @NelsonMok Getting data into a dataset object is as simple as writing Dataset[data] -- although Dataset does not currently do a very good job of visualizing arbitrary JSON data. You might be better off to leave it in association form and access it using Query or the techniques described in (3111) or (103965). $\endgroup$
    – WReach
    Mar 13 '16 at 5:13

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