Created
February 4, 2021 13:27
-
-
Save jenska/2a83fb61104d0890de58e3684cfa7c68 to your computer and use it in GitHub Desktop.
JSON unmarshaller for custom types
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" | |
"io/ioutil" | |
"strings" | |
"time" | |
) | |
type ( | |
Bool bool | |
DateTime time.Time | |
Tweet struct { | |
Id uint64 `json:"id"` | |
Text string `json:"text"` | |
IsRetweet Bool `json:"isRetweet"` | |
IsDeleted Bool `json:"isDeleted"` | |
Device string `json:"device"` | |
Favorites uint32 `json:"favorites"` | |
Retweets uint32 `json:"retweets"` | |
Date DateTime `json:"date"` | |
IsFlagged Bool `json:"isFlagged"` | |
} | |
) | |
var tweets []Tweet | |
func (t Tweet) String() string { | |
return fmt.Sprintf("%s: %s", time.Time(t.Date).Format("2006-01-02 15:04:05"), t.Text) | |
} | |
func (b *Bool) UnmarshalJSON(bytes []byte) error { | |
*b = bytes[1] == 't' | |
return nil | |
} | |
func (dt *DateTime) UnmarshalJSON(bytes []byte) error { | |
var s string | |
if err := json.Unmarshal(bytes, &s); check(err) { | |
if d, err := time.Parse("2006-01-02 15:04:05", s); check(err) { | |
*dt = DateTime(d) | |
} | |
} | |
return nil | |
} | |
func check(err error) bool { | |
if err != nil { | |
panic(err) | |
} | |
return true | |
} | |
func main() { | |
// tweets_01-08-2021.json downloaed from https://www.thetrumparchive.com/ | |
if jsonFile, err := ioutil.ReadFile("tweets_01-08-2021.json"); check(err) { | |
json.Unmarshal(jsonFile, &tweets) | |
fmt.Println(len(tweets)) | |
for _, tweet := range tweets { | |
if strings.Contains(tweet.Text, "I.Q.") { | |
fmt.Println(tweet) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment