Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse an inner field in a nested JSON object

Tags:

json

go

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.

like image 252
keks Avatar asked Nov 27 '12 21:11

keks


People also ask

How do I access JSON nested data?

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.

How can we parse a nested JSON object in Java?

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.

How do I read a nested JSON file in Python?

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.

How do I filter nested JSON data in Python?

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.


1 Answers

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) } 
like image 125
Daniel Avatar answered Oct 13 '22 09:10

Daniel