douzhan1963
2019-06-18 12:31
浏览 193
已采纳

在Golang中将TXT文件转换为Json [关闭]

I'm struggling trying to convert a text file to JSON. I can't use python for limitations in the implementation so it needs to be in Go.

I have this file structure

VAULT_ADDR=https://address.com
SECRET_USERNAME={{tata/user}}
SECRET_PASSWORD={{tata/pass}}
SECRET_SLACK_TOKEN={{tata/token}}

SECRET_CONTENTFUL_SPACE_ID={{tata/space}}
SECRET_CONTENTFUL_ACCESS_TOKEN={{tata/stuff}}

SECRET_NEW_RELIC_TOKEN={{tata/tata}}

I'd need to covert it for a JSON structure, I tried a lot of things but don't know if I should use a structure, interface or how to do this.

would like to convert for this:

[  
{  
    "name":"VAULT_ADDR",
    "value":"https://address.com"
},
{  
    "name":"SECRET_USERNAME",
    "value":"{{tata/user}}"
},
{  
    "name":"SECRET_PASSWORD",
    "value":"{{tata/pass}}"
},
{  
    "name":"SECRET_SLACK_TOKEN",
    "value":"{{tata/token}}"
},
{  
    "name":"SECRET_CONTENTFUL_SPACE_ID",
    "value":"{{tata/space}}"
},
{  
    "name":"SECRET_CONTENTFUL_ACCESS_TOKEN",
    "value":"{{tata/stuff}}"
},
{  
    "name":"SECRET_NEW_RELIC_TOKEN",
    "value":"{{tata/tata}}"
}
]

this is my code so far...

package main

import (
  "flag"
  "fmt"
  "io/ioutil"
  "log"
  "os"
  "strings"
)

 var (
   file string
)

 func main() {

   flag.StringVar(&file, "f", "", "file path")
   flag.Parse()

   data, err := os.Open(file)
   if err != nil {
      log.Fatal(err)
   }
   defer data.Close()

   file, err := ioutil.ReadAll(data)

   converter := string(file)

   s := strings.Split(converter, "=")

   for _, line := range s {
      parser := "name" + line

      fmt.Println(parser)
   }

 }

My code output:

name= VAULT_ADDR value
name= https://address.com
SECRET_USERNAME value
name= {{tata/user}}
SECRET_PASSWORD value
name= {{tata/pass}}
SECRET_SLACK_TOKEN value
name= {{tata/token}}

SECRET_CONTENTFUL_SPACE_ID value
name= {{tata/space}}
SECRET_CONTENTFUL_ACCESS_TOKEN value
name= {{tata/stuff}}

SECRET_NEW_RELIC_TOKEN value
name= {{tata/tata}} value

thank you

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题