gpt4 book ai didi

arrays - 构建对象的Json对象并将其写入文件

转载 作者:行者123 更新时间:2023-12-01 22:43:45 27 4
gpt4 key购买 nike

我正在尝试获取从Go API接收到的字符串数组,并将它们以怪异的json列表格式写入文件。没有括号[],因此我必须为数组中的每个字符串值创建一个“维”。我正在尝试使用类型/结构来做到这一点,但我一直陷于困境(Go的新手)。我应该尝试仅使用 map ,还是有办法实现?

这是我现在正在使用的代码:

package main

import (
"fmt"
"io/ioutil"
)

type Dimension struct {
SQL, Type string
}

type Measure struct {
Type string
DrillMembers []string
}

func check(e error) {
if e != nil {
panic(e)
}
}

func main() {
a := []string{"country", "year", "gdpPercap", "lifeExp", "pop", "continent"}
cubeSchema := "measures: {\n count: {\n type: `count`,\n drillMembers: "
for i, s := range a {
cubeSchema += s
fmt.Println(cubeSchema)
fmt.Println(i)
}

fileText := []byte(cubeSchema)
fmt.Println(cubeSchema)
err := ioutil.WriteFile("test.js", fileText, 0644)
check(err)
}

这就是我需要的输出看起来:
measures: {
count: {
type: `count`,
drillMembers: [country]
}
},

dimensions: {
country: {
sql: `country`,
type: `string`
},

year: {
sql: `year`,
type: `string`
},

gdppercap: {
sql: `gdppercap`,
type: `string`
},

lifeexp: {
sql: `lifeexp`,
type: `string`
},

pop: {
sql: `pop`,
type: `string`
},

continent: {
sql: `continent`,
type: `string`
}
}

现在,我一直被以下输出卡住:
measures: {
count: {
type: `count`,
drillMembers: countryyeargdpPercaplifeExppopcontinent

最佳答案

package main

import (
"fmt"
"io/ioutil"
)

func check(e error) {
if e != nil {
panic(e)
}
}

func main() {
schema := `measures: {
count: {
type: 'count',
drillMembers: [country]
}
},

dimensions: {
`
a := []string{"country", "year", "gdpPercap", "lifeExp", "pop", "continent"}
var cubeSchema string
for _, s := range a {
cubeSchema += s + ": {\n\tsql: " + s + ",\n\ttype: `string`\n},\n"
}

fileText := []byte(schema + cubeSchema + "}\n}")
fmt.Println(cubeSchema)
err := ioutil.WriteFile("test.js", fileText, 0644)
check(err)
}

检查此代码。

关于arrays - 构建对象的Json对象并将其写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61916400/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com