英文:
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"} }
我的目标:
-
逐行读取文件。
-
将每一行转换为可读格式
{ "body_bytes_sent": "474", "params" : {"device_id": "1234567890"} }
-
将此字符串转换为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:
-
Read the file line by line.
-
Convert each line to a readable format
{ "body_bytes_sent": "474", "params" : {"device_id": "1234567890"} }
-
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)
}
英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论