Go – 如何将包含十六进制字符的文本文件解码/转换为可读字符串

huangapple go评论94阅读模式
英文:

Go - How to decode/convert a txt file contains hex chars into readable string

问题

我有一个日志文件,每一行都是一个JSON。由于一些Nginx安全原因,日志以十六进制格式保存(例如,字符"将被转换为\x22)。这是一个JSON行的示例:

 { "body_bytes_sent": "474", "params": {"device_id": "1234567890"} }

我的目标:

  1. 逐行读取文件。

  2. 将每一行转换为可读格式

    { "body_bytes_sent": "474", "params" : {"device_id": "1234567890"} }
    
  3. 将此字符串转换为JSON对象,以便我可以操作它。

任何帮助将不胜感激。

英文:

I've got a log file, where each line is a JSON. Due to some Nginx security reasons, the logs are being saved in a hexadecimal format (e.g. the char " will be converted to \x22). Here is an example of a JSON line:

 { "body_bytes_sent": "474", "params": {\x22device_id\x22: \x221234567890\x22} }

My goal:

  1. Read the file line by line.

  2. Convert each line to a readable format

    { "body_bytes_sent": "474", "params" : {"device_id": "1234567890"} }
    
  3. Convert this string into a JSON object so I could manipulate it.

Any help will be appreciated.

答案1

得分: 4

你可以使用strconv.Unquote将字符串转换为普通字符串:

package main

import (
	"encoding/json"
	"fmt"
	"strconv"
)

func main() {
	
	// 这是你的输入字符串的样子...
	qs := "{\"device_id\": \"1234567890\"}"

	// 现在让我们将其转换为普通字符串
	// 注意它必须看起来像Go字符串文字,所以我们使用Sprintf
	s, err := strconv.Unquote(fmt.Sprintf(`"%s"`, qs))
	if err != nil {
		panic(err)
	}
	fmt.Println(s)

	// 为了保险起见,让我们看看它是否可以被解码。
	// 提示:它可以被成功解码!
	var v map[string]interface{}
	if err := json.Unmarshal([]byte(s), &v); err != nil {
		panic(err)

	}
	fmt.Println(v)
}

Playground

英文:

You can use strconv.Unquote to convert the string to a normal one:

package main

import (
	"encoding/json"
	"fmt"
	"strconv"
)

func main() {
	
	// this is what your input string looks like...
	qs := "{\\x22device_id\\x22: \\x221234567890\\x22}"

	// now let's convert it to a normal string
    // note that it has to look like a Go string literal so we're
    // using Sprintf
	s, err := strconv.Unquote(fmt.Sprintf(`"%s"`, qs))
	if err != nil {
		panic(err)
	}
	fmt.Println(s)

	// just for good measure, let's see if it can actually be decoded.
    // SPOILER ALERT: It decodes just fine!
	var v map[string]interface{}
	if err := json.Unmarshal([]byte(s), &v); err != nil {
		panic(err)

	}
	fmt.Println(v)
}

<kbd>Playground</kbd>

huangapple
  • 本文由 发表于 2015年11月26日 16:19:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/33933577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定