英文:
Writing and reading json in Go (Golang)
问题
所以,假设我有一些以JSON格式存储的文章。
{"articles": [{"title": "这是一篇很棒的文章。", "content": "这篇文章真的很棒吗?"}, {"title": "在StackOverflow上提问", "content": "这很容易。"}]}
我想按照它们的顺序阅读这些文章,即先是"这是一篇很棒的文章",然后是"在StackOverflow上提问"。然后,我需要按顺序编辑或写入它们,这样当我有一篇新文章时,它将变为:
{"articles": [{"title": "新文章", "content": "内容"}, {"title": "这是一篇很棒的文章。", "content": "这篇文章真的很棒吗?"}, {"title": "在StackOverflow上提问", "content": "这很容易。"}]}
或者更新为:
{"articles": [{"title": "新文章", "content": "新文章的内容"}, {"title": "这是一篇很棒的文章。", "content": "这篇文章真的很棒吗?"}, {"title": "在StackOverflow上提问", "content": "这很容易。"}]}
我打算通过文章的标题来操作它们,但是我还没有找到在Go语言中进行这种写入和更新的方法。你能帮我解决这个问题吗?
我已经能够通过两个接口进行读取,但是我不知道如何进行写入和更新。
type Articles struct {
Article []Article
}
type Article struct {
Title string
Content string
}
英文:
So, say I have some articles in JSON.
{"articles": [{"title": "This is an awesome post.", "content": "How amazing is this article actually?"}, {"title": "Asking a question on StackOerflow", "content": "It's very easy."}]}
So I want to read the articles in their order i.e. This is an awesome post, then Asking a question on StackOverflow. Then I have to edit or write to them in order, so when I have a new post it will be:
{"articles": [{"title": "New Post", "content": "Content"},{"title": "This is an awesome post.", "content": "How amazing is this article actually?"}, {"title": "Asking a question on StackOerflow", "content": "It's very easy."}]}
Or updating:
{"articles": [{"title": "New Post", "content": "Content of new post"},{"title": "This is an awesome post.", "content": "How amazing is this article actually?"}, {"title": "Asking a question on StackOerflow", "content": "It's very easy."}]}
I intend to manipulate articles by their titles, but I haven't been able to get such manipulation in Go (the writing and updating). Can you help me out?
I have been able to get reading with 2 interfaces, but I don't know how to write, update.
type Articles struct {
Article []Article
}
type Article struct {
Title string
Content string
}
答案1
得分: 1
这是另一种方法:http://play.golang.org/p/K-eYSrn1tx
我将在这里复制代码以便查看:
package main
import (
"encoding/json"
"fmt"
)
type JsonDoc struct {
Articles []Article
}
type Article struct {
Title string
Content string
}
func main() {
s := `{"articles": [
{"title": "这是一篇很棒的文章。",
"content": "这篇文章真的很棒吗?"},
{"title": "在StackOverflow上提问",
"content": "这很容易。"}]}`
doc := JsonDoc{}
// 玩具示例。在真实应用中,我们不应忽略这里可能出现的错误。
json.Unmarshal([]byte(s), &doc)
fmt.Printf("之前: %#v\n", doc)
// 注意:在切片的前面添加元素有点昂贵。
// 考虑在后面添加,或者使用更合适的数据表示方式。
frontArticle := Article{Title: "另一篇文章",
Content: "这是它的内容。"}
doc.Articles = append([]Article{frontArticle},
doc.Articles...)
fmt.Printf("之后: %#v\n", doc)
// 玩具示例:在真实应用中,我们不应忽略这里可能出现的错误。
marshalled, _ := json.Marshal(&doc)
fmt.Printf("%s\n", marshalled)
}
你会注意到,编组输出与输入在键名方面略有不同。输入使用小写键,但我们的输出产生了大写键!你需要告诉JSON编码器更多关于外部表示的信息,以便在编组时正确处理。这是一种使用结构字段标签的方法:http://play.golang.org/p/HHeMQUcCDV
英文:
Here's another approach: http://play.golang.org/p/K-eYSrn1tx
I'll copy the code here for easy of viewing:
package main
import (
"encoding/json"
"fmt"
)
type JsonDoc struct {
Articles []Article
}
type Article struct {
Title string
Content string
}
func main() {
s := `{"articles": [
{"title": "This is an awesome post.",
"content": "How amazing is this article actually?"},
{"title": "Asking a question on StackOverflow",
"content": "It's very easy."}]}`
doc := JsonDoc{}
// Toy example. In a real application, we should not ignore
// the possibility of an error here.
json.Unmarshal([]byte(s), &doc)
fmt.Printf("Before: %#v\n", doc)
// Note: adding to the front of a slice is a bit expensive.
// Consider adding to the back, or use a data representation
// that's more appropriate.
frontArticle := Article{Title: "Another article",
Content: "Here's its content."}
doc.Articles = append([]Article{frontArticle},
doc.Articles...)
fmt.Printf("After: %#v\n", doc)
// Toy example: in a real application, we should not ignore
// the possibility of an error here.
marshalled, _ := json.Marshal(&doc)
fmt.Printf("%s\n", marshalled)
}
You'll notice that the marshalled output is slightly different from the input in terms of the key names. The input used lowercased keys, but our output is producing uppercased keys! You'll need to tell the JSON encoder a bit more about the external representation so it can do the right thing at marshal time. Here's one way to do it, using struct field tags: http://play.golang.org/p/HHeMQUcCDV
答案2
得分: 0
好的,以下是翻译好的部分:
好的,我已经解决了:
s := `{"articles": [{"title": "This is an awesome post.", "content": "How amazing is this article actually?"}, {"title": "Asking a question on StackOverflow", "content": "It's very easy."}]}`
items := &Articles{}
json.Unmarshal([]byte(s), items)
theLength := len(items.Article) + 1
newArray := make([]Article, theLength)
newArray[0] = Article{"My New Title", "My New Content"}
for i := 1; i < theLength; i++ {
newArray[i] = items.Article[i-1]
}
newItems := &Articles{}
newItems.Article = newArray
// 现在 newItems 是新的接口
希望对你有帮助!
英文:
Ok, I've solved it:
s := `{"articles": [{"title": "This is an awesome post.", "content": "How amazing is this article actually?"}, {"title": "Asking a question on StackOverflow", "content": "It's very easy."}]}`
items := &Articles{}
json.Unmarshal([]byte(s), items)
theLength := len(items.Article) + 1
newArray := make([]Article, theLength)
newArray[0] = Article{"My New Title", "My New Content"}
for i := 1; i < theLength; i++ {
newArray[i] = items.Article[i-1]
}
newItems := &Articles{}
newItems.Article = newArray
//now newItems is the new interface
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论