I have a JSON object similar to this one:
{ "name": "Cain", "parents": { "mother" : "Eve", "father" : "Adam" } }
Now I want to parse "name" and "mother" into this struct:
struct { Name String Mother String `json:"???"` }
I want to specify the JSON field name with the json:...
struct tag, however I don't know what to use as tag, because it is not the top object I am interested in. I found nothing about this in the encoding/json
package docs nor in the popular blog post JSON and Go. I also tested mother
, parents/mother
and parents.mother
.
Accessing nested json objects is just like accessing nested arrays. Nested objects are the objects that are inside an another object. In the following example 'vehicles' is a object which is inside a main object called 'person'. Using dot notation the nested objects' property(car) is accessed.
We can parse a nested JSON object using the getString(index) method of JSONArray. This is a convenience method for the getJSONString(index). getString() method and it returns a string value at the specified position.
Python has built in functions that easily imports JSON files as a Python dictionary or a Pandas dataframe. Use pd. read_json() to load simple JSONs and pd. json_normalize() to load nested JSONs.
As the loaded json data is just nested lists and dicts, you can use the ordinary list/dict operations; in particular, list comprehension is useful. Show activity on this post. import json # Loding the data pathToFile = "bb. json" with open(pathToFile, 'r') as file: content = file.
You could use structs so long as your incoming data isn't too dynamic.
http://play.golang.org/p/bUZ8l6WgvL
package main import ( "fmt" "encoding/json" ) type User struct { Name string Parents struct { Mother string Father string } } func main() { encoded := `{ "name": "Cain", "parents": { "mother": "Eve", "father": "Adam" } }` // Decode the json object u := &User{} err := json.Unmarshal([]byte(encoded), &u) if err != nil { panic(err) } // Print out mother and father fmt.Printf("Mother: %s\n", u.Parents.Mother) fmt.Printf("Father: %s\n", u.Parents.Father) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With