Home > OS >  How to use golang to convert a multi-line json to one-line json?
How to use golang to convert a multi-line json to one-line json?

Time:06-14

How can I convert a multi-line json to a one-line json using golang? From

{
          "release_date": "2004-11-09",
          "status": "retired",
          "engine": "Gecko",
          "engine_version": "1.7"
        }

To {"release_date":"2004-11-09","status":"retired","engine":"Gecko","engine_version":"1.7"}

CodePudding user response:

Create a regexp that matches line breaks and following whitespace:

lb := regexp.MustCompile(`\r?\n\s*`)

Use that regexp to replace line breaks with space:

doc = lb.ReplaceAllString(doc, " ") // when doc is a string

or

doc = lb.ReplaceAll(doc, " ")       // when doc is a []byte

This transformation is safe because because the regexp does not match any part of a JSON document value (the carriage return and newline bytes are not valid in a JSON string).

CodePudding user response:

Unmarshal the multi-line JSON into a struct (or alternatively a map[string]any{}) and then marshal it to a string without any indent options. So, something like this:

    v := struct {
        ReleaseDate string `json:"release_date"`
        Status      string `json:"status"`
        Engine      string `json:"engine"`
        Version     string `json:"engine_version"`
    }{}

    if err := json.Unmarshal([]byte(s), &v); err != nil {
        fmt.Printf("ERROR: %v\n", err)
    } else if bytes, err := json.Marshal(v); err != nil {
        fmt.Printf("ERROR: %v\n", err)
    } else {
        fmt.Printf("%v\n", string(bytes))
    }

(Go Playground)

CodePudding user response:

If you dont know which kind of json you will get just use like this

package main

import (
    "encoding/json"
    "fmt"
)

const js = `
{
    "release_date": "2004-11-09",
    "status": "retired",
    "engine": "Gecko",
    "1": "1.7"
}
`

func main() {
    helper := make(map[string]interface{})

    err := json.Unmarshal([]byte(js), &helper)
    if err != nil {
        fmt.Printf("json.Unmarshal([]byte(s), &helper) failed. Error:  %v\n", err)
        return
    } 
    
    bytes, err := json.Marshal(helper)
    if err != nil {
        fmt.Printf("json.Marshal(helper) failed. Error:  %v\n", err)
        return
    }
    
    fmt.Println(string(bytes))
        
}

Try here

And don't use replacing spaces because you can damage json values

  • Related