Suche senden
Hochladen
Unmarshalling json lists with multiple types
•
0 gefällt mir
•
604 views
M
mattyw
Folgen
My talk from the London go user group on 27 March 2013
Weniger lesen
Mehr lesen
Technologie
Melden
Teilen
Melden
Teilen
1 von 10
Jetzt herunterladen
Downloaden Sie, um offline zu lesen
Empfohlen
Ποδηλατικός Τουρισμός Δήμος Χερσονήσου Κρήτη - Cycling Tourism in Hersonissos...
Ποδηλατικός Τουρισμός Δήμος Χερσονήσου Κρήτη - Cycling Tourism in Hersonissos...
My Chersonissos
Raising the profile of research
Raising the profile of research
Natalie Blackburn
Evaluační výzkum v zahraniční rozvojové spolupráci - příležitosti pro student...
Evaluační výzkum v zahraniční rozvojové spolupráci - příležitosti pro student...
Inka Pibilova
ท่องเที่ยวไปตามเส้นทางประวัติศาสตร์สายพัทลุง8 9-10 (2)
ท่องเที่ยวไปตามเส้นทางประวัติศาสตร์สายพัทลุง8 9-10 (2)
ศานติ มีจิตเกษม
Introdution - Fujitsu PRIMEQUEST
Introdution - Fujitsu PRIMEQUEST
Andrew Wong
CONTABILIDAD: HISTORIA Y ACTUALIDAD
CONTABILIDAD: HISTORIA Y ACTUALIDAD
Elkin Peña
üBertritt13
üBertritt13
HomepageAdmin
2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
Marius Sescu
Empfohlen
Ποδηλατικός Τουρισμός Δήμος Χερσονήσου Κρήτη - Cycling Tourism in Hersonissos...
Ποδηλατικός Τουρισμός Δήμος Χερσονήσου Κρήτη - Cycling Tourism in Hersonissos...
My Chersonissos
Raising the profile of research
Raising the profile of research
Natalie Blackburn
Evaluační výzkum v zahraniční rozvojové spolupráci - příležitosti pro student...
Evaluační výzkum v zahraniční rozvojové spolupráci - příležitosti pro student...
Inka Pibilova
ท่องเที่ยวไปตามเส้นทางประวัติศาสตร์สายพัทลุง8 9-10 (2)
ท่องเที่ยวไปตามเส้นทางประวัติศาสตร์สายพัทลุง8 9-10 (2)
ศานติ มีจิตเกษม
Introdution - Fujitsu PRIMEQUEST
Introdution - Fujitsu PRIMEQUEST
Andrew Wong
CONTABILIDAD: HISTORIA Y ACTUALIDAD
CONTABILIDAD: HISTORIA Y ACTUALIDAD
Elkin Peña
üBertritt13
üBertritt13
HomepageAdmin
2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
Marius Sescu
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
Lars Bell
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
Lonnie McRorey
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
UiPathCommunity
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
Miki Katsuragi
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Precisely
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Mark Simos
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
BookNet Canada
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
Mattias Andersson
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
Addepto
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
Commit University
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
Dubai Multi Commodity Centre
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
Florian Wilhelm
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
DianaGray10
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
Sergiu Bodiu
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
Dilum Bandara
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
Kalema Edgar
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
ScyllaDB
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
RankYa
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
Sri Ambati
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
Manik S Magar
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
Expeed Software
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
Pixeldarts
Weitere ähnliche Inhalte
Kürzlich hochgeladen
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
Lars Bell
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
Lonnie McRorey
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
UiPathCommunity
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
Miki Katsuragi
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Precisely
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Mark Simos
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
BookNet Canada
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
Mattias Andersson
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
Addepto
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
Commit University
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
Dubai Multi Commodity Centre
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
Florian Wilhelm
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
DianaGray10
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
Sergiu Bodiu
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
Dilum Bandara
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
Kalema Edgar
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
ScyllaDB
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
RankYa
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
Sri Ambati
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
Manik S Magar
Kürzlich hochgeladen
(20)
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
Empfohlen
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
Expeed Software
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
Pixeldarts
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
marketingartwork
Skeleton Culture Code
Skeleton Culture Code
Skeleton Technologies
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
Neil Kimberley
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
contently
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
Albert Qian
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
Search Engine Journal
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
SpeakerHub
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
Clark Boyd
Getting into the tech field. what next
Getting into the tech field. what next
Tessa Mero
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Lily Ray
How to have difficult conversations
How to have difficult conversations
Rajiv Jayarajah, MAppComm, ACC
Introduction to Data Science
Introduction to Data Science
Christy Abraham Joy
Time Management & Productivity - Best Practices
Time Management & Productivity - Best Practices
Vit Horky
The six step guide to practical project management
The six step guide to practical project management
MindGenius
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
RachelPearson36
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Applitools
Empfohlen
(20)
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
Skeleton Culture Code
Skeleton Culture Code
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
Getting into the tech field. what next
Getting into the tech field. what next
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
How to have difficult conversations
How to have difficult conversations
Introduction to Data Science
Introduction to Data Science
Time Management & Productivity - Best Practices
Time Management & Productivity - Best Practices
The six step guide to practical project management
The six step guide to practical project management
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unmarshalling json lists with multiple types
1.
Unmarshalling json lists
with multiple types Also called "Fun with json & types" or "Help me find another way"
2.
{
"things": [ { "name": "Alice", "age": 37 }, { "city": "Ipoh", "country": "Malaysia" }, { "name": "Bob", "age": 36 }, { "city": "Northampton", "country": "England" } ] } map[string]Person|Place
3.
To get us
started type Person struct { Name string Age int } type Place struct { City string Country string } func solution(jsonString []byte) ([]Person []Place) {} Error handling is allowed to be good -> non existent and inconsistent
4.
{
"things": [ { "name": "Alice", "age": 37 }, { "city": "Ipoh", "country": "Malaysia" }, { "name": "Bob", "age": 36 }, { "city": "Northampton", "country": "England" } ] } map[string]Person|Place map[string][]map[string]interface{}
5.
Map & type
assert func solutionA(jsonStr []byte) ([]Person, []Place) { func addPerson(persons []Person, item map[string]interface persons := []Person{} {}) []Person { places := []Place{} name, _ := item["name"].(string) var data map[string][]map[string]interface{} age, _ := item["age"].(int) err := json.Unmarshal(jsonStr, &data) person := Person{name, age} if err != nil { persons = append(persons, person) fmt.Println(err) return persons return persons, places } } for i := range data["things"] { func addPlace(places []Place, item map[string]interface{}) []Place { item := data["things"][i] city, _ := item["city"].(string) if item["name"] != nil { country, _ := item["city"].(string) persons = addPerson(persons, item) place := Place{city, country} } else { places = append(places, place) places = addPlace(places, item) return places } } } return persons, places }
6.
{
"things": [ { "name": "Alice", "age": 37 }, { "city": "Ipoh", "country": "Malaysia" }, { "name": "Bob", "age": 36 }, { "city": "Northampton", "country": "England" } ] } map[string]Person|Place map[string][]Person&Place??
7.
Mixed Type Struct func
solutionB(jsonStr []byte) ([]Person, []Place) { type Mixed struct { persons := []Person{} Name string `json:"name"` places := []Place{} Age int `json:"age"` var data map[string][]Mixed City string `json:"city"` err := json.Unmarshal(jsonStr, &data) Country string `json:"country"` if err != nil { } fmt.Println(err) return persons, places } for i := range data["things"] { item := data["things"][i] if item.Name != "" { persons = append(persons, Person{item.Name, item.Age}) } else { places = append(places, Place{item.City, item.Country}) } } return persons, places }
8.
{
"things": [ { "name": "Alice", "age": 37 }, { "city": "Ipoh", "country": "Malaysia" }, { "name": "Bob", "age": 36 }, { "city": "Northampton", "country": "England" } ] } map[string]Person|Place map[string][]PleaseLeaveAsJson
9.
json.RawMessage func solutionC(jsonStr []byte)
([]Person, []Place) { func addPersonC(thing json.RawMessage, people []Person) [] people := []Person{} Person { places := []Place{} person := Person{} var data map[string][]json.RawMessage if err := json.Unmarshal(thing, &person); err != nil { err := json.Unmarshal(jsonStr, &data) fmt.Println(err) if err != nil { } else { fmt.Println(err) if person != *new(Person) { return people, places people = append(people, person) } } for _, thing := range data["things"] { } people = addPersonC(thing, people) return people places = addPlaceC(thing, places) } } func addPlaceC(thing json.RawMessage, places []Place) []Place { return people, places place := Place{} } if err := json.Unmarshal(thing, &place); err != nil { fmt.Println(err) } else { if place != *new(Place) { places = append(places, place) } } return places }
10.
https://gist.github.com/mattyw/4556603 http://bit.ly/10Os7Tp <- Original
blog post
Jetzt herunterladen