码迷,mamicode.com
首页 > Web开发 > 详细

go与json

时间:2014-11-14 13:56:23      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   os   sp   文件   数据   div   

Go语言对JSON进行编码和解码

http://outofmemory.cn/code-snippet/3766/Go-language-to-JSON-to-coding-jiema

package main

import (
    "fmt"
    "encoding/json"
)

func main() {
    // json encode
    j1 := make(map[string]interface{})
    j1["name"] = "outofmemory"
    j1["url"] = "http://outofmemory.cn/"

    js1, err := json.Marshal(j1)
    if err != nil {
        panic(err)
    }

    println(string(js1))

    // json decode
    j2 := make(map[string]interface{})
    err = json.Unmarshal(js1, &j2)
    if err != nil {
        panic(err)
    }

    fmt.Printf("%#v\n", j2)
}

Go语言从文件中读取Json数据

http://www.oschina.net/code/snippet_197499_22659 

{
    "13918098715":"63120523",
    "13918098719":"73314985",
    "13918098718":"82752863",
    "13918098714":"92440329",
        "13918094183":"35875678",
    "13918094187":"45562314",
    "13918094186":"54292576",
    "13918094185":"63906263",
    "13918094189":"73460548",
    "13918094364":"45717870"
}

package main
 
import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)
 
var xxx = map[string]string{}
 
func readFile(filename string) (map[string]string, error) {
    bytes, err := ioutil.ReadFile(filename)
    if err != nil {
        fmt.Println("ReadFile: ", err.Error())
        return nil, err
    }
 
    if err := json.Unmarshal(bytes, &xxx); err != nil {
        fmt.Println("Unmarshal: ", err.Error())
        return nil, err
    }
 
    return xxx, nil
}
 
func main() {
    xxxMap, err := readFile("xxx.json")
    if err != nil {
        fmt.Println("readFile: ", err.Error())
        return nil, err
    }
 
    fmt.Println(xxxMap)
}

 

 

aa

go与json

标签:blog   http   io   ar   os   sp   文件   数据   div   

原文地址:http://www.cnblogs.com/jingzhishen/p/4096986.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!