7

I'm brand new to Mathematica and I imported a json:

data = ImportString["{\"x\":1,\"y\":1}", "json"]

and result:

{"x" -> 1, "y" -> 1}

Now data denotes {"x" -> 1, "y" -> 1}.

I want to get the value of sub property x(I tried data.x -- since I'm a Java programmer -- didn't work), but I don't know how to do it. I read some document about json, but all those doc presents is how to import and export json.

Could any one give me some suggestions?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Sayakiss
  • 859
  • 7
  • 13

1 Answers1

11

The result of importing a file in JSON format is a list of rules. For information about ways to use rules, see the documentation for Applying Transformation Rules.

Here is an example:

data = ImportString["{\"x\":1, \"y\":{\"a\":2, \"b\":[3, 4]}}", "JSON"]
(* {"x" -> 1, "y" -> {"a" -> 2, "b" -> {3, 4}}} *)

Retrieving a top-level property is straight-forward:

"x" /. data
(* 1 *)

Retrieving nested properties is a bit more awkward:

"b" /. ("y" /. data)
(* {3, 4} *)

("b" /. ("y" /. data))[[2]]
(* 4 *)

Starting with Mathematica version 10.2, the new RawJSON format is a little more convenient to work with:

data = ImportString["{\"x\":1, \"y\":{\"a\":2, \"b\":[3, 4]}}", "RawJSON"]
(* <| "x" -> 1, "y" -> <| "a" -> 2, "b" -> {3, 4} |>|> *)

It returns associations for objects instead of rule lists. Associations offer a nicer syntax for accessing elements:

data[["x"]]
(* 1 *)

data[["y", "b"]]
(* {3, 4} *)

data[["y", "b", 2]]
(* 4 *)

When processing really complicated JSON trees, the Dataset and Query functionality might prove to be useful.

WReach
  • 68,832
  • 4
  • 164
  • 269