


Flattening Nested JSON
Navigating complex JSON structures with multiple levels of nesting can be challenging in Go. When it becomes necessary to flatten these nested structures into a more streamlined format, custom solutions are often needed.
In the presented scenario, the task is to flatten a JSON response that contains a nested Social type with a further nested Facebook type. The goal is to eliminate the intermediate Facebook type and flatten its properties into the Social type.
Custom UnmarshalJSON Functions
To achieve this, we can utilize the power of Go's UnmarshalJSON function, which allows you to customize how JSON is decoded into a struct. Here's how to implement this for flattening nested JSON:
<code class="go">type Social struct { // ... existing properties ... FacebookLikes uint32 `json:"-"` FacebookShares uint32 `json:"-"` FacebookComments uint32 `json:"-"` FacebookTotal uint32 `json:"-"` } func (s *Social) UnmarshalJSON(data []byte) error { m := make(map[string]interface{}) if err := json.Unmarshal(data, &m); err != nil { return err } m = Flatten(m) // Extract nested Facebook properties if fbMap, ok := m["Facebook"].(map[string]interface{}); ok { s.FacebookLikes = fbMap["FacebookLikes"].(uint32) s.FacebookShares = fbMap["FacebookShares"].(uint32) s.FacebookComments = fbMap["FacebookComments"].(uint32) s.FacebookTotal = fbMap["FacebookTotal"].(uint32) } return nil }</code>
Flatten Helper Function
The Flatten helper function is responsible for removing nested maps and replacing them with dot-delimited keys:
<code class="go">func Flatten(m map[string]interface{}) map[string]interface{} { o := make(map[string]interface{}) for k, v := range m { switch child := v.(type) { case map[string]interface{}: nm := Flatten(child) for nk, nv := range nm { o[k+"."+nk] = nv } default: o[k] = v } } return o }</code>
Using this approach, the nested Facebook type is removed, and its properties are flattened into the Social type, resulting in a more concise and manageable data structure.
The above is the detailed content of How to Flatten Nested JSON Structures in Go Using Custom UnmarshalJSON Functions?. For more information, please follow other related articles on the PHP Chinese website!

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

The article discusses managing Go module dependencies via go.mod, covering specification, updates, and conflict resolution. It emphasizes best practices like semantic versioning and regular updates.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
