Golang逐行解析JSON值为文本的方法
Golang逐行解析JSON值为文本的方法 我想将 https://sonar.omnisint.io/subdomains/ejemplo.com 这个值输出为以下格式。
有人能帮忙吗?
_dmarc.ejemplo.com _mta-sts.ejemplo.com deathstar.ejemplo.com docs.ejemplo.com ejemplo.com ejemplo.ejemplo.com es.ejemplo.com ftp.ejemplo.com host.ejemplo.com listas.ejemplo.com m.ejemplo.com mail.ejemplo.com miservidor.ejemplo.com misitio.ejemplo.com ns.ejemplo.com otro.ejemplo.com server1.ejemplo.com sitio.ejemplo.com target.ejemplo.com test2.ejemplo.com ubuzimbra.ejemplo.com us.ejemplo.com ws01.ejemplo.com www.ejemplo.com wwww.ejemplo.com zimbra8.ejemplo.com
更多关于Golang逐行解析JSON值为文本的方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html
嘿,这对我帮助很大。我现在明白了。
谢谢你的帮助!
更多关于Golang逐行解析JSON值为文本的方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
你好,
我不太清楚你是在询问如何打印API调用返回的字符串列表,还是如何通过调用URL来获取这个列表。
var values []string
if err := json.Unmarshal([]byte(response), &values); err != nil {
panic("something bad happened")
}
for _, item := range values {
fmt.Println(item)
}
假设 response 变量包含了API调用返回的JSON字符串,这段代码会将字符串逐行打印出来。
在Go中逐行解析JSON值并输出为文本格式,可以使用标准库的encoding/json配合流式解析。以下是示例代码:
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
func main() {
// 获取JSON数据
resp, err := http.Get("https://sonar.omnisint.io/subdomains/ejemplo.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
// 使用json.Decoder进行流式解析
decoder := json.NewDecoder(resp.Body)
// 读取起始的'['字符
if _, err := decoder.Token(); err != nil {
panic(err)
}
// 逐行解析数组中的每个元素
for decoder.More() {
var subdomain string
if err := decoder.Decode(&subdomain); err != nil {
panic(err)
}
// 输出格式化结果
if strings.HasPrefix(subdomain, "_") {
fmt.Printf("%s\n", subdomain)
} else {
fmt.Printf("[%s](http://%s)\n", subdomain, subdomain)
}
}
// 读取结束的']'字符
if _, err := decoder.Token(); err != nil {
panic(err)
}
}
如果JSON数据是本地文件,可以使用以下变体:
package main
import (
"encoding/json"
"fmt"
"os"
"strings"
)
func main() {
file, err := os.Open("subdomains.json")
if err != nil {
panic(err)
}
defer file.Close()
decoder := json.NewDecoder(file)
// 解析JSON数组
var subdomains []string
if err := decoder.Decode(&subdomains); err != nil {
panic(err)
}
// 逐行处理
for _, subdomain := range subdomains {
if strings.HasPrefix(subdomain, "_") {
fmt.Printf("%s\n", subdomain)
} else {
fmt.Printf("[%s](http://%s)\n", subdomain, subdomain)
}
}
}
对于需要处理嵌套JSON结构的情况:
package main
import (
"encoding/json"
"fmt"
"strings"
)
func main() {
// 示例JSON数据(实际应从网络或文件读取)
jsonData := `["_dmarc.ejemplo.com","_mta-sts.ejemplo.com","deathstar.ejemplo.com"]`
var subdomains []string
if err := json.Unmarshal([]byte(jsonData), &subdomains); err != nil {
panic(err)
}
for _, subdomain := range subdomains {
if strings.HasPrefix(subdomain, "_") {
fmt.Printf("%s\n", subdomain)
} else {
fmt.Printf("[%s](http://%s)\n", subdomain, subdomain)
}
}
}
这些代码示例演示了如何:
- 从URL获取JSON数据并流式解析
- 根据子域名是否以下划线开头选择不同的输出格式
- 处理JSON数组中的每个字符串元素
- 输出符合要求的文本格式
第一个示例直接处理网络响应,适合大数据量的流式处理;第二个示例适合本地文件处理;第三个示例展示基本的JSON解析。根据实际数据源选择合适的方法。

