# How to parse JSON

please forgive me if this is obvious, but I have some JSON:

ExportString[
<|"Names" -> <|
"Sister" -> "Nina",
"Brothers" -> {<|"Older" -> "John","Younger" -> "Jake"|>},
"DOB" -> {<|
"Nina" -> 2001,
"location" -> "Miami"|>,
<|"John" -> 2017,
"location" -> "Hell"|>}|>, "RawJSON"]


(NOTE, I am converting an association to JSON just for the purposes of this post. In reality I am making a URL request and it is returning JSON).

I want to separate the JSON at depth 1. So I want to return an association of "Names" and an Association of "DOB". Is there a function similar to Lookup that works with JSON or some other way to index JSON?

Thank you.

EDIT: Actually, I would like to keep "Names" as JSON.

EDIT (per comments): Here's what i'm looking for structurally: The first output I want is the JSON corresponding to "Names":

out1 =
{
"Names":{
"Sister":"Nina",
"Brothers":[
{
"Older":"John",
"Younger":"Jake"
}
],
}
}


The second output I want is an Association of the values corresponding to "DOB":

out2 =
<|"DOB"->{<|
"Nina" -> 2001,
"location" -> "Miami"|>,
<|"John" -> 2017,
"location" -> "Hell"|>}|>

• For your simple case, can you please manually type out, what structure you are seeking? Do you want an association that contains JSON as values or something else? – halirutan May 12 '17 at 2:10
• It's still not clear what you're looking for. If your association is called a, does ExportString[a["Names"]] do what you want? – yohbs May 12 '17 at 3:21
• Also, the title of the question is "How to parse JSON" while the content does not seem to be about parsing at all but rather about constructing JSON from associations. Is that the case? – yohbs May 12 '17 at 3:22
• What do you mean "still not clear"? I haven't responded yet. Read the note in the post. I already have the JSON, I want to get the elements out of it. I'll be adding an edit in 2 minutes showing structurally What I'm talking about. – Joe Blow May 12 '17 at 3:32
• I just included the ExportString so you could see the JSON I am working with. Ignore it. Just copy and past the original code into Mathematica and the output is where we're starting from. – Joe Blow May 12 '17 at 3:48

The example JSON string:

json = ExportString[<|
"Names" -> <|
"Sister" -> "Nina",
"Brothers" -> {<|"Older" -> "John", "Younger" -> "Jake"|>},
|>,
"DOB" -> {
<|"Nina" -> 2001, "location" -> "Miami"|>,
<|"John" -> 2017, "location" -> "Hell"|>}
|>, "RawJSON"];


Import it as an association:

assoc = ImportString[json, "RawJSON"];


Here is how to get an association for each key at the first level:

<|# -> assoc[[#]]|> & /@ Keys[assoc]


Here is how to get a JSON string for each key at the first level:

ExportString[<|# -> assoc[[#]]|>, "JSON"] & /@ Keys[assoc]