dshkmamau65777662 2018-03-18 06:13
浏览 576
已采纳

在golang中将数组插入json对象

I am processing data from a text file with go and would like to ouput a json record like this:

[{
        "ship": "RMS Titanic",
        "crew": [{
            "name": "Captain Smith"
        }, {
            "name": "First Officer Murdoch"
        }],
        "passengers": [{
            "name": "Jack Dawson"
        }, {
            "name": "Rose Dewitt Bukater"
        }]
    },
    {
        "ship": "ship2",
        "crew": [{
            "name": "crew 1"
        }, {
            "name": "crew 2"
        }],
        "passengers": [{
            "name": "passenger 1"
        }, {
            "name": "passenger 2"
        }]
    }
]

Here is a snippet from my code:

package main

import (
        "fmt"
        "encoding/json"
)

func main() {
        var crew []map[string]string
        var passengers []map[string]string

        s1 := map[string]string{ "name": "RMS Titanic"}
        j1, _ := json.Marshal(s1)
        fmt.Printf("j1: %s
", string(j1))

        s2 := map[string]string{ "name": "Captain Smith" }
        crew = append(crew, s2)
        s2 = map[string]string{ "name": "First Officer Murdoch" }
        crew = append(crew, s2)
        j2, _ := json.Marshal(crew)
        fmt.Printf("j2: %s
", string(j2))

        s3 := map[string]string{ "name": "Jack Dawson"}
        passengers = append(passengers, s3)
        s3 = map[string]string{ "name": "Rose Dewitt Bukater" }
        passengers = append(passengers, s3)

        j3, _ := json.Marshal(passengers)
        fmt.Printf("j3: %s
", string(j3))

        s4 :=  map[string]string{"crew": string(j2), "passengers": string(j3)}
        j4, _ := json.Marshal(s4)
        fmt.Printf("j4: %s
", string(j4))

}

Output:

j1: {"name":"RMS Titanic"}
j2: [{"name":"Captain Smith"},{"name":"First Officer Murdoch"}]
j3: [{"name":"Jack Dawson"},{"name":"Rose Dewitt Bukater"}]
j4: {"crew":"[{\"name\":\"Captain Smith\"},{\"name\":\"First Officer Murdoch\"}]","passengers":"[{\"name\":\"Jack Dawson\"},{\"name\":\"Rose Dewitt Bukater\"}]"}

I am processing the ship data in j1, the crew data in j2 and the passengers data in j3.

I have managed to merge j2 and j3 together into j4, but the quotation mark s are escapaded, how un-escape the quotation marks ?

How to insert j1 data in there so the output match the json output I wish for ?

  • 写回答

1条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥50 有没有大佬看一下关于思科的这道题怎么做
      • ¥30 求十字路口交通灯S7-200plc,今天早上八点前。
      • ¥20 如何用智能手表oppowatch3实现个人热点功能
      • ¥15 运营商打开wanpush会有怎么样的危害
      • ¥15 Java编程题,定义一个时钟
      • ¥15 Python面向对象编程——生成多项式的一阶导数
      • ¥15 在编写C++程序遇到了问题
      • ¥15 java程序查找字符串中所有的回文并输出
      • ¥15 怎么让只支持对.exe 和.dll文件进行加壳的加壳器,同时让它也支持php文件加壳呢
      • ¥15 这两个数学公式什么意思?