7
$\begingroup$

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?

$\endgroup$
2

1 Answer 1

11
$\begingroup$

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.

$\endgroup$

Your Answer

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

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