Created
June 30, 2020 08:23
-
-
Save m7shapan/e00cb6641f5ee7a468485bf8e89638b1 to your computer and use it in GitHub Desktop.
How to use NJSON Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"github.com/m7shapan/njson" | |
) | |
var jsonString string = ` | |
{ | |
"coord": { | |
"lon": -0.13, | |
"lat": 51.51 | |
}, | |
"weather": [ | |
{ | |
"id": 300, | |
"main": "Drizzle", | |
"description": "light intensity drizzle", | |
"icon": "09d" | |
} | |
], | |
"base": "stations", | |
"main": { | |
"temp": 280.32, | |
"pressure": 1012, | |
"humidity": 81, | |
"temp_min": 279.15, | |
"temp_max": 281.15 | |
}, | |
"visibility": 10000, | |
"wind": { | |
"speed": 4.1, | |
"deg": 80 | |
}, | |
"clouds": { | |
"all": 90 | |
}, | |
"dt": 1485789600, | |
"sys": { | |
"type": 1, | |
"id": 5091, | |
"message": 0.0103, | |
"country": "GB", | |
"sunrise": 1485762037, | |
"sunset": 1485794875 | |
}, | |
"id": 2643743, | |
"name": "London", | |
"cod": 200 | |
} | |
` | |
func main() { | |
njsonUnmarshaling() | |
jsonUnmarshaling() | |
} | |
func njsonUnmarshaling() { | |
type Weather struct { | |
Location string `njson:"name"` | |
Weather string `njson:"weather.0.main"` | |
Description string `njson:"weather.0.description"` | |
Temperature float32 `njson:"main.temp"` | |
MinTemperature float32 `njson:"main.temp_min"` | |
MaxTemperature float32 `njson:"main.temp_max"` | |
} | |
var weather Weather | |
err := njson.Unmarshal([]byte(jsonString), &weather) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("%+v\n", weather) | |
} | |
func jsonUnmarshaling() { | |
type Weather struct { | |
Location string | |
Weather string | |
Description string | |
Temperature float32 | |
MinTemperature float32 | |
MaxTemperature float32 | |
} | |
type TmpWeather struct { | |
Location string `json:"name"` | |
Weather []struct { | |
Weather string `json:"main"` | |
Description string `json:"description"` | |
} `json:"weather"` | |
Temperature struct { | |
Temperature float32 `json:"temp"` | |
MinTemperature float32 `json:"temp_min"` | |
MaxTemperature float32 `json:"temp_max"` | |
} `json:"main"` | |
} | |
var tmpW TmpWeather | |
err := json.Unmarshal([]byte(jsonString), &tmpW) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("%+v\n", tmpW) | |
weather := Weather{ | |
Location: tmpW.Location, | |
Weather: tmpW.Weather[0].Weather, | |
Description: tmpW.Weather[0].Description, | |
Temperature: tmpW.Temperature.Temperature, | |
MinTemperature: tmpW.Temperature.MinTemperature, | |
MaxTemperature: tmpW.Temperature.MaxTemperature, | |
} | |
fmt.Printf("%+v\n", weather) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment