我正在尝试将 json 转换为 golang 嵌套结构。它只是部分工作。大多数字段都不能正确解析,尽管有些可以。为什么不将来自 json 的所有数据都转换为 golang 结构?我的猜测是我的 json 格式和 golang 结构之间有一些错误,但我没有看到它。发帖让其他人关注这个问题。
当我运行程序时,机器 ip 地址被解码,但测试运行 id 却没有。这是我的主要方法的输出:
test run id:
machine ip:172.25.148.39
这是我的 golang 代码:
package main
import (
"encoding/json"
"bytes"
"io/ioutil"
"runtime"
"log"
)
func main() {
var testRunConfig TestRunConfig
testRunConfigJson := ReadFile("testrun-config.json")
err := json.Unmarshal([]byte(testRunConfigJson), &testRunConfig)
if err != nil {
HandleError(err)
}
println("test run id:" + testRunConfig.Id)
println("machine ip:" + testRunConfig.Machines[0].IP)
}
//Logs the error, the function and the line number where it was generated
func HandleError(err error) (bool) {
b := false
if err != nil {
// notice that we're using 1, so it will actually log the where
// the error happened, 0 = this function, we don't want that.
pc, fn, line, _ := runtime.Caller(1)
log.Printf("[error] in %s[%s:%d] %v", runtime.FuncForPC(pc).Name(), fn, line, err)
b = true
panic(err)
}
return b
}
func ReadFile(fileName string) string {
dat, err := ioutil.ReadFile(fileName)
HandleError(err)
return string(dat)
}
//http://json2struct.mervine.net/
type Machine struct {
IP string
Interfaces []Interface
Containers []Container
CmdBuffer bytes.Buffer
}
type InetAddress struct {
Addr string
DelayMS int
}
type Interface struct {
Name string
InetAddresses []InetAddress
}
type Volume struct {
Localhost string
Volume string
}
type NetworkTopology struct {
Host string
Port string
}
type Container struct {
Image string
Mem string
Cpu float64
Disk string
Volume Volume
NodeId int
ServiceType string
InstanceId string
Port string
NetworkTopology []NetworkTopology
Args map[string]string
//"machine" element being a member of a Container is helpful for code flow/logic,
//but is not required as part of the data model (it's duplicate data).
//This is why it's private (not capitalized). Think of it as a "transient" in java.
machine Machine
}
type TestRunConfig struct {
Id string
Machines []Machine
}
这是正在转换的 json:
{
"Id:": "testRunId",
"Machines": [
{
"Ip": "172.25.148.39",
"Interfaces": [
{
"Name": "ems3f0",
"InetAddresses": [
{
"Addr": "10.0.0.x/16",
"DelayMS": 0
}
]
},
{
"Name": "ems3f1",
"InetAddresses": [
{
"Addr": "10.5.0.x/16",
"DelayMS": 5
},
{
"Addr": "10.15.0.x/16",
"DelayMS": 15
},
{
"Addr": "10.25.0.x/16",
"DelayMS": 25
}
]
}
],
"Containers": [
{
"Image": "docker-core:1",
"Mem": "20GB",
"Cpu": 1.0,
"Disk": "20GB",
"Volume": {
"Localhost": "/mnt/md0/${containerId}",
"Volume": "/root/.btcd${containerId}"
},
"NodeId": 0,
"ServiceType": "core",
"InstanceId": "core1",
"Port": "f(nodeid, serviceid, instanceId -> port #)",
"NetworkTopology": [
{
"Host": "ip.address",
"Port": "some.port"
}
],
"Args": {
"database": "${volume}/init-data.csv.tgz",
"listenPort": "1234",
"sendPort": "1234"
}
},
{
"Image": "docker-wallet:1",
"Mem": "20GB",
"Cpu": 1.0,
"Disk": "20GB",
"Volume": {
"Localhost": "/mnt/md0/${containerId}",
"Volume": "/root/.btcd${containerId}"
},
"NodeId (cluster)": 0,
"ServiceType": "wallet",
"InstanceId": "1...100",
"Port": "portNum",
"Args": {
"Database": "${volume}/init-data.csv.tgz",
"ListenPort": "1234",
"SendPort": "1234"
}
}
]
}
]
}
最佳答案
在您的 JSON 中,您有一个拼写错误(一个额外的冒号)。您将有问题的字段称为 "Id:" 而不是 "Id"。删除 : 代码应该可以工作了!
请注意,您的 NodeId 字段也可能不会填充,因为在 JSON 中,您将其称为 "NodeId (cluster)" 而不是 "NodeId"。 JSON 和 Go 中的字段名称必须完全匹配。如果您想在 JSON 中使用与 Go 中不同的字段名称,请使用 JSON 名称注释您的结构:
type Example struct {
Name string `json:"firstName"`
...
}
关于json - golang 结构仅从 json 中部分解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46875811/
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
给定一个复杂的对象层次结构,幸运的是它不包含循环引用,我如何实现支持各种格式的序列化?我不是来讨论实际实现的。相反,我正在寻找可能会派上用场的设计模式提示。更准确地说:我正在使用Ruby,我想解析XML和JSON数据以构建复杂的对象层次结构。此外,应该可以将该层次结构序列化为JSON、XML和可能的HTML。我可以为此使用Builder模式吗?在任何提到的情况下,我都有某种结构化数据-无论是在内存中还是文本中-我想用它来构建其他东西。我认为将序列化逻辑与实际业务逻辑分开会很好,这样我以后就可以轻松支持多种XML格式。 最佳答案 我最
我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":
您将如何构建一个简单的Sinatra应用程序?我正在制作,我希望该应用具有以下功能:“应用程序”更像是一个包含所有信息的管理仪表板。然后另一个应用程序将通过REST访问信息。我还没有创建仪表板,只是从数据库中获取东西session和身份验证(尚未实现)您可以上传图片,其他应用可以显示这些图片我已经使用RSpec创建了一个测试文件通过Prawn生成报告目前的设置是这样的:app.rbtest_app.rb因为我实际上只有应用程序和测试文件。到目前为止,我已经将Datamapper用于ORM,将SQLite用于数据库。这是我的第一个Ruby/Sinatra项目,所以欢迎任何和所有建议-我应
我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("
我想编写一个ruby脚本来递归复制目录结构,但排除某些文件类型。因此,给定以下目录结构:folder1folder2file1.txtfile2.txtfile3.csfile4.htmlfolder2folder3file4.dll我想复制这个结构,但不包含.txt和.cs文件。因此,生成的目录结构应如下所示:folder1folder2file4.htmlfolder2folder3file4.dll 最佳答案 您可以使用查找模块。这是一个代码片段:require"find"ignored_extensions=[".cs"
我在一个简单的RailsAPI中有以下Controller代码:classApi::V1::AccountsControllerehead:not_foundendendend问题在于,生成的json具有以下格式:{id:2,name:'Simpleaccount',cash_flows:[{id:1,amount:34.3,description:'simpledescription'},{id:2,amount:1.12,description:'otherdescription'}]}我需要我生成的json是camelCase('cashFlows'而不是'cash_flows'
我正在学习如何使用JSONgem解析和生成JSON。我可以轻松地创建数据哈希并将其生成为JSON;但是,在获取一个类的实例(例如Person实例)并将其所有实例变量放入哈希中以转换为JSON时,我脑袋放屁。这是我遇到问题的例子:require"json"classPersondefinitialize(name,age,address)@name=name@age=age@address=addressenddefto_jsonendendp=Person.new('JohnDoe',46,"123ElmStreet")p.to_json我想创建一个.to_json方法,这样我就可以获
我正在构建一个带有Rails后端的JS应用程序,为了不混淆snake和camelcases,我想通过从服务器返回camelcase键名来规范化这一切。因此,当从API返回时,user.last_name将返回user.lastName。我如何实现这一点?谢谢!编辑:添加Controller代码classApi::V1::UsersController 最佳答案 我的方法是使用ActiveModelSerializer和json_api适配器:在你的Gemfile中,添加:gem'active_model_serializers'创建