在Go(Golang)写作和阅读json

时间:2014-07-24 10:07:41

标签: json go

所以,说我在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."}]}

所以我想按顺序阅读文章,即这是一篇很棒的文章,然后在StackOverflow上提问。然后我必须按顺序编辑或写入它们,所以当我有一个新帖子时,它将是:

{"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."}]}

或更新:

{"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."}]}

我打算用他们的头衔操纵文章,但我还没有能够在Go(写作和更新)中获得这样的操作。你能救我一下吗?

我已经能够阅读2个接口,但我不知道如何写,更新。

type Articles struct {
    Article []Article
}

type Article struct {
    Title   string
    Content string
}

2 个答案:

答案 0 :(得分: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": "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)
}

您会注意到,关键名称的编组输出与输入略有不同。输入使用了小写键,但我们的输出正在生成大写键!你需要告诉JSON编码器更多关于外部表示的信息,这样它才能在编组时做正确的事情。这是使用struct field标签的一种方法:http://play.golang.org/p/HHeMQUcCDV

答案 1 :(得分: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
    //now newItems is the new interface