How to decode nested JSON with Golang is a challenge faced by many developers when dealing with complex data structures. In this article, PHP editor Banana will introduce you in detail how to use the JSON package in Golang to parse and process nested JSON data. By studying the content of this article, you will be able to easily handle various complex JSON structures and achieve more efficient data parsing and processing. Whether you are a beginner or an experienced developer, this article will provide you with useful tips and sample code to help you solve the difficult problem of JSON decoding. Let’s explore the method of decoding nested JSON in Golang!
I'm trying to decode a nested json as part of a request that contains a file and data.
The data looks like this
{data: {"date_required":null}}
I didn't include the full error initially because I forgot to log it.
2023/11/17 23:40:35 error in decoding request body data 2023/11/17 23:40:35 invalid character '.' looking for beginning of value
I think this error may be caused by the form data not being JSON, but don't know how to fix it. My Flutter code looks like it's sending valid JSON. The content type is multipart/form-data
which may be causing the error. I believe this content type is required for the file upload portion of my code.
The request comes from my Flutter client, the code is as follows:
final multipartFile = http.MultipartFile.fromBytes('file', bytes, filename: file?.name); final request = http.MultipartRequest('POST', Uri.parse(user.fileUrl)); request.files.add(multipartFile); request.headers.addAll(headers); String dateRequiredStr = dateRequired != null ? jsonEncode({'date_required': dateRequired}) : jsonEncode({'date_required': null}); request.fields['data'] = dateRequiredStr;
In my go API I'm doing this.
Model (edited based on answer below):
type FileRequiredDate struct { DateRequired pgtype.Date `json:"date_required"` } type FileRequiredDateData struct { Data FileRequiredDate `json:"data"` }
Code:
func (rs *appResource) uploadTranscriptAudioFile(w http.ResponseWriter, r *http.Request) { start := time.Now() const maxUploadSize = 500 * 1024 * 1024 // 500 Mb var requiredByDate FileRequiredDateData decoder := json.NewDecoder(r.Body) err := decoder.Decode(&requiredByDate) if err != nil { log.Println("error in decoding request body data") log.Println(err.Error()) http.Error(w, err.Error(), http.StatusBadRequest) return } file, handler, err := r.FormFile("file") if err != nil { log.Println(err) http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) return } defer file.Close() fileSize := handler.Size if fileSize > maxUploadSize { http.Error(w, "FILE_TOO_BIG", http.StatusBadRequest) return } fileName := handler.Filename
httputil.DumpRequest
-> Content type: multipart/form-data
Edit: Based on the answer to this question, I edited the code as follows:
mr, err := r.MultipartReader() if err != nil { log.Println(err) http.Error(w, err.Error(), http.StatusInternalServerError) return } for { part, err := mr.NextPart() // This is OK, no more parts if err == io.EOF { break } // Some error if err != nil { log.Println("multipart reader other error") http.Error(w, err.Error(), http.StatusInternalServerError) return } log.Println(part.FormName()) if part.FormName() == "data" { log.Println("multipart reader found multipart form name data") decoder := json.NewDecoder(r.Body) err = decoder.Decode(&requiredByDate) if err != nil { log.Println("error in decoding request body data") log.Println(err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError) return } } } if part.FormName() == "file" { file, handler, err := r.FormFile("file") <-- error here if err != nil { log.Println("error getting form file") log.Println(err.Error()) http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusInternalServerError) return } defer file.Close() guid := xid.New() userId := getUserFromJWT(r) user, err := getUser(rs, int64(userId)) if err != nil { log.Println("user not found") log.Println(err.Error()) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } err = uploadToMinio(rs, file, fileSize, fileName, guid.String(), userId) ----
This gives me this output:
2023/11/17 23:23:30 data 2023/11/17 23:23:30 file
edit:
I solved the current problem by using decoder := json.NewDecoder(part)
instead of decoder := json.NewDecoder(r.Body)
Now I'm getting a error while getting the form file . It seems like I should use parts somehow, but parts don't have file properties. Since I added the form data to the multipart request, r.Body is no longer available. This looks like a different problem.
While this does not solve the 404 issue (please update your question with the request handler code), your structure does not appear to match what you are sending. You can do the following to resolve this issue:
type FileRequiredDate struct { DateRequired pgtype.Date `json:"date_required"` } type FileRequiredDateData struct { Data FileRequiredDate `json:"data"` }
This should decode the request body as expected.
For 404s, you should double check that the request path and method sent by the client code match the server request handler path and method.
The above is the detailed content of How to decode this nested json with Golang?. For more information, please follow other related articles on the PHP Chinese website!