我正在解组一个结构,我希望它以格式化的方式进行打印。
我的代码(https://play.golang.org/p/D0KwGP6Cxa0)当前产生以下输出:
main.ADIStruct{CondensedADI:[]main.CondensedADI{main.CondensedADI{Name:"Type", Value:"title"}, main.CondensedADI{Name:"Title", Value:"Ste Life_S01_E10_"}, main.CondensedADI{Name:"Title_Brief", Value:"Ste Life_S01_E10_HD"}, main.CondensedADI{Name:"Episode_Name", Value:"Cody Goes to Camp"}, main.CondensedADI{Name:"Episode_ID", Value:"10"}, main.CondensedADI{Name:"Summary_Short", Value:"Zack is excited to finally get rid of his brother when Cody leaves for math camp."}, main.CondensedADI{Name:"Rating", Value:"TV-G"}, main.CondensedADI{Name:"Run_Time", Value:"00:22:50"}, main.CondensedADI{Name:"Display_Run_Time", Value:"00:23"}, main.CondensedADI{Name:"Year", Value:"2005"}, main.CondensedADI{Name:"Closed_Captioning", Value:"Y"}, main.CondensedADI{Name:"Genre", Value:"Family"}, main.CondensedADI{Name:"Billing_ID", Value:"00000"}, main.CondensedADI{Name:"Actors_Display", Value:"Ashley Tisdale ( Maddie ), Brenda Song ( London ), Cole Sprouse ( Cody ), Dylan Sprouse ( Zack ), Kim Rhodes ( Carey ), Phill Lewis ( Moseby )"}, main.CondensedADI{Name:"Licensing_Window_Start", Value:"2019-05-15 00:00:00"}, main.CondensedADI{Name:"Licensing_Window_End", Value:"2019-10-31 00:00:00"}, main.CondensedADI{Name:"Preview_Period", Value:"0"}, main.CondensedADI{Name:"Display_As_New", Value:"7"}, main.CondensedADI{Name:"Display_As_Last_Chance", Value:"7"}, main.CondensedADI{Name:"Provider_QA_Contact", Value:"DATG.DL-VOD.Support@disney.com"}, main.CondensedADI{Name:"Suggested_Price", Value:"0.00"}, main.CondensedADI{Name:"Category", Value:"Disney Channel HD/Suite Life"}}}
我希望它仅具有名称和值,并且在每个项目之后都有一个新行。像这样:
Name:"Type", Value:"title"
Name:"Title", Value:"Ste Life_S01_E10_"
有什么想法可以做到吗?
答案 0 :(得分:3)
Go标准库中有一个函数,该函数采用interface{}
并生成缩进的JSON输出:json.MarshalIndent
。
这是一个示例如何将其应用于用例(https://play.golang.org/p/3geUEEHESSa)的示例:
s, _ := json.MarshalIndent(b, "", "\t");
fmt.Print(string(s))
虽然与您所期望的不完全相同,但这会生成易于读取的JSON输出:
{
"CondensedADI": [
{
"Name": "Type",
"Value": "title"
},
{
"Name": "Title",
"Value": "Ste Life_S01_E10_"
},
...
答案 1 :(得分:1)
这可能是一个重复问题的重复答案,但是json.MarshalIndent()
的一个很好的替代选择是使用go-spew,它将为您提供更多详细信息和格式设置:https://github.com/davecgh/go-spew