本文整理汇总了Golang中encoding/json.Unmarshal函数的典型用法代码示例。如果您正苦于以下问题:Golang Unmarshal函数的具体用法?Golang Unmarshal怎么用?Golang Unmarshal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Unmarshal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: makeRawConfigFromV1Config
func makeRawConfigFromV1Config(imageJSON []byte, rootfs *image.RootFS, history []image.History) (map[string]*json.RawMessage, error) {
var dver struct {
DockerVersion string `json:"docker_version"`
}
if err := json.Unmarshal(imageJSON, &dver); err != nil {
return nil, err
}
useFallback := versionPkg.Version(dver.DockerVersion).LessThan("1.8.3")
if useFallback {
var v1Image image.V1Image
err := json.Unmarshal(imageJSON, &v1Image)
if err != nil {
return nil, err
}
imageJSON, err = json.Marshal(v1Image)
if err != nil {
return nil, err
}
}
var c map[string]*json.RawMessage
if err := json.Unmarshal(imageJSON, &c); err != nil {
return nil, err
}
c["rootfs"] = rawJSON(rootfs)
c["history"] = rawJSON(history)
return c, nil
}
示例2: compareObjects
// What we're trying to do here is compare the JSON encoded values, but we can't
// to a simple encode + string compare since JSON encoding is not ordered. So
// what we do is JSON encode, then JSON decode into untyped maps, and then
// finally do a recursive comparison.
func compareObjects(t *testing.T, expected interface{}, actual interface{}) {
expectedBytes, err := json.Marshal(expected)
if err != nil {
t.Fatal(err)
return
}
actualBytes, err := json.Marshal(actual)
if err != nil {
t.Fatal(err)
return
}
var expectedUntyped, actualUntyped map[string]interface{}
err = json.Unmarshal(expectedBytes, &expectedUntyped)
if err != nil {
t.Fatal(err)
return
}
err = json.Unmarshal(actualBytes, &actualUntyped)
if err != nil {
t.Fatal(err)
return
}
if !reflect.DeepEqual(expectedUntyped, actualUntyped) {
t.Fatalf("Expected %s, got %s", string(expectedBytes), string(actualBytes))
}
}
示例3: UtilCreateNetworkMode
func UtilCreateNetworkMode(c *check.C, networkMode string) {
config := map[string]interface{}{
"Image": "busybox",
"HostConfig": map[string]interface{}{"NetworkMode": networkMode},
}
status, body, err := sockRequest("POST", "/containers/create", config)
c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusCreated)
var container types.ContainerCreateResponse
if err := json.Unmarshal(body, &container); err != nil {
c.Fatal(err)
}
status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
c.Assert(err, check.IsNil)
c.Assert(status, check.Equals, http.StatusOK)
var containerJSON types.ContainerJSON
if err := json.Unmarshal(body, &containerJSON); err != nil {
c.Fatal(err)
}
if containerJSON.HostConfig.NetworkMode != runconfig.NetworkMode(networkMode) {
c.Fatalf("Mismatched NetworkMode, Expected %s, Actual: %s ", networkMode, containerJSON.HostConfig.NetworkMode)
}
}
示例4: modUser
func (u *httpAuthUserAPI) modUser(ctx context.Context, req *authUserAPIAction) (*User, error) {
resp, body, err := u.client.Do(ctx, req)
if err != nil {
return nil, err
}
if err = assertStatusCode(resp.StatusCode, http.StatusOK); err != nil {
var sec authError
err = json.Unmarshal(body, &sec)
if err != nil {
return nil, err
}
return nil, sec
}
var user User
if err = json.Unmarshal(body, &user); err != nil {
var userR UserRoles
if urerr := json.Unmarshal(body, &userR); urerr != nil {
return nil, err
}
user.User = userR.User
for _, r := range userR.Roles {
user.Roles = append(user.Roles, r.Role)
}
}
return &user, nil
}
示例5: ManifestMatchesImage
// ManifestMatchesImage returns true if the provided manifest matches the name of the image.
func ManifestMatchesImage(image *Image, newManifest []byte) (bool, error) {
dgst, err := digest.ParseDigest(image.Name)
if err != nil {
return false, err
}
v, err := digest.NewDigestVerifier(dgst)
if err != nil {
return false, err
}
var canonical []byte
switch image.DockerImageManifestMediaType {
case schema2.MediaTypeManifest:
var m schema2.DeserializedManifest
if err := json.Unmarshal(newManifest, &m); err != nil {
return false, err
}
_, canonical, err = m.Payload()
if err != nil {
return false, err
}
case schema1.MediaTypeManifest, "":
var m schema1.SignedManifest
if err := json.Unmarshal(newManifest, &m); err != nil {
return false, err
}
canonical = m.Canonical
default:
return false, fmt.Errorf("unsupported manifest mediatype: %s", image.DockerImageManifestMediaType)
}
if _, err := v.Write(canonical); err != nil {
return false, err
}
return v.Verified(), nil
}
示例6: UnmarshalJSON
func (t *Tags) UnmarshalJSON(data []byte) error {
var tags []Tag
switch data[0] {
case '[':
// Unmarshal into []Tag
if err := json.Unmarshal(data, &tags); err != nil {
return err
}
case '{':
// Unmarshal into map[string]string
tagMap := make(map[string]string)
if err := json.Unmarshal(data, &tagMap); err != nil {
return err
}
// Convert to []Tag
for k, v := range tagMap {
tags = append(tags, Tag{k, v})
}
default:
return ErrUnableToUnmarshalJSON
}
*t = tags
return nil
}
示例7: TestViewQueryMultipleViews
//Tests #1109, where design doc contains multiple views
func TestViewQueryMultipleViews(t *testing.T) {
var rt restTester
//Define three views
response := rt.sendAdminRequest("PUT", "/db/_design/foo", `{"views": {"by_fname": {"map": "function (doc, meta) { emit(doc.fname, null); }"},"by_lname": {"map": "function (doc, meta) { emit(doc.lname, null); }"},"by_age": {"map": "function (doc, meta) { emit(doc.age, null); }"}}}`)
assertStatus(t, response, 201)
response = rt.sendRequest("PUT", "/db/doc1", `{"fname": "Alice", "lname":"Ten", "age":10}`)
assertStatus(t, response, 201)
response = rt.sendRequest("PUT", "/db/doc2", `{"fname": "Bob", "lname":"Seven", "age":7}`)
assertStatus(t, response, 201)
response = rt.sendAdminRequest("GET", "/db/_design/foo/_view/by_age", ``)
assertStatus(t, response, 200)
var result sgbucket.ViewResult
json.Unmarshal(response.Body.Bytes(), &result)
assert.Equals(t, len(result.Rows), 2)
assert.DeepEquals(t, result.Rows[0], &sgbucket.ViewRow{ID: "doc2", Key: 7.0, Value: interface{}(nil)})
assert.DeepEquals(t, result.Rows[1], &sgbucket.ViewRow{ID: "doc1", Key: 10.0, Value: interface{}(nil)})
response = rt.sendAdminRequest("GET", "/db/_design/foo/_view/by_fname", ``)
assertStatus(t, response, 200)
json.Unmarshal(response.Body.Bytes(), &result)
assert.Equals(t, len(result.Rows), 2)
assert.DeepEquals(t, result.Rows[0], &sgbucket.ViewRow{ID: "doc1", Key: "Alice", Value: interface{}(nil)})
assert.DeepEquals(t, result.Rows[1], &sgbucket.ViewRow{ID: "doc2", Key: "Bob", Value: interface{}(nil)})
response = rt.sendAdminRequest("GET", "/db/_design/foo/_view/by_lname", ``)
assertStatus(t, response, 200)
json.Unmarshal(response.Body.Bytes(), &result)
assert.Equals(t, len(result.Rows), 2)
assert.DeepEquals(t, result.Rows[0], &sgbucket.ViewRow{ID: "doc2", Key: "Seven", Value: interface{}(nil)})
assert.DeepEquals(t, result.Rows[1], &sgbucket.ViewRow{ID: "doc1", Key: "Ten", Value: interface{}(nil)})
}
示例8: Status
func (plugin *execNetworkPlugin) Status(namespace string, name string, id kubeletTypes.DockerID) (*network.PodNetworkStatus, error) {
out, err := utilexec.New().Command(plugin.getExecutable(), statusCmd, namespace, name, string(id)).CombinedOutput()
glog.V(5).Infof("Status 'exec' network plugin output: %s, %v", string(out), err)
if err != nil {
return nil, err
}
if string(out) == "" {
return nil, nil
}
findVersion := struct {
api.TypeMeta `json:",inline"`
}{}
err = json.Unmarshal(out, &findVersion)
if err != nil {
return nil, err
}
// check kind and version
if findVersion.Kind != "" && findVersion.Kind != "PodNetworkStatus" {
errStr := fmt.Sprintf("Invalid 'kind' returned in network status for pod '%s'. Valid value is 'PodNetworkStatus', got '%s'.", name, findVersion.Kind)
return nil, errors.New(errStr)
}
switch findVersion.APIVersion {
case "":
fallthrough
case "v1beta1":
networkStatus := &network.PodNetworkStatus{}
err = json.Unmarshal(out, networkStatus)
return networkStatus, err
}
errStr := fmt.Sprintf("Unknown version '%s' in network status for pod '%s'.", findVersion.APIVersion, name)
return nil, errors.New(errStr)
}
示例9: RetrieveStatelessApplication
func RetrieveStatelessApplication(name string) (*StatelessSerializable, error) {
stateless, err := GetStorage().LoadStatelessApplication(name)
if err != nil {
log.Error("Load stateless application error %s", err)
return nil, err
}
replicationControllerJsonMap := make(map[string]interface{})
err = json.Unmarshal(stateless.replicationControllerJson, &replicationControllerJsonMap)
if err != nil {
log.Error("Unmarshal replication controller json for stateless application error %s", err)
return nil, err
}
serviceJsonMap := make(map[string]interface{})
err = json.Unmarshal(stateless.serviceJson, &serviceJsonMap)
if err != nil {
log.Error("Unmarshal service json for stateless application error %s", err)
return nil, err
}
statelessSerializable := &StatelessSerializable{
stateless.Name,
stateless.Description,
replicationControllerJsonMap,
serviceJsonMap,
stateless.Environment,
}
return statelessSerializable, nil
}
示例10: CanEmulateNetworkConditions
// CanEmulateNetworkConditions - Tells whether emulation of network conditions is supported.
// Returns - result - True if emulation of network conditions is supported.
func (c *Network) CanEmulateNetworkConditions() (bool, error) {
resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Network.canEmulateNetworkConditions"})
if err != nil {
return false, err
}
var chromeData struct {
Result struct {
Result bool
}
}
if resp == nil {
return false, &gcdmessage.ChromeEmptyResponseErr{}
}
// test if error first
cerr := &gcdmessage.ChromeErrorResponse{}
json.Unmarshal(resp.Data, cerr)
if cerr != nil && cerr.Error != nil {
return false, &gcdmessage.ChromeRequestErr{Resp: cerr}
}
if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
return false, err
}
return chromeData.Result.Result, nil
}
示例11: GetCertificateDetails
// GetCertificateDetails - Returns details for the given certificate.
// certificateId - ID of the certificate to get details for.
// Returns - result - Certificate details.
func (c *Network) GetCertificateDetails(certificateId int) (*NetworkCertificateDetails, error) {
paramRequest := make(map[string]interface{}, 1)
paramRequest["certificateId"] = certificateId
resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Network.getCertificateDetails", Params: paramRequest})
if err != nil {
return nil, err
}
var chromeData struct {
Result struct {
Result *NetworkCertificateDetails
}
}
if resp == nil {
return nil, &gcdmessage.ChromeEmptyResponseErr{}
}
// test if error first
cerr := &gcdmessage.ChromeErrorResponse{}
json.Unmarshal(resp.Data, cerr)
if cerr != nil && cerr.Error != nil {
return nil, &gcdmessage.ChromeRequestErr{Resp: cerr}
}
if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
return nil, err
}
return chromeData.Result.Result, nil
}
示例12: GetCookies
// GetCookies - Returns all browser cookies. Depending on the backend support, will return detailed cookie information in the <code>cookies</code> field.
// Returns - cookies - Array of cookie objects.
func (c *Network) GetCookies() ([]*NetworkCookie, error) {
resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Network.getCookies"})
if err != nil {
return nil, err
}
var chromeData struct {
Result struct {
Cookies []*NetworkCookie
}
}
if resp == nil {
return nil, &gcdmessage.ChromeEmptyResponseErr{}
}
// test if error first
cerr := &gcdmessage.ChromeErrorResponse{}
json.Unmarshal(resp.Data, cerr)
if cerr != nil && cerr.Error != nil {
return nil, &gcdmessage.ChromeRequestErr{Resp: cerr}
}
if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
return nil, err
}
return chromeData.Result.Cookies, nil
}
示例13: GetResponseBody
// GetResponseBody - Returns content served for the given request.
// requestId - Identifier of the network request to get content for.
// Returns - body - Response body. base64Encoded - True, if content was sent as base64.
func (c *Network) GetResponseBody(requestId string) (string, bool, error) {
paramRequest := make(map[string]interface{}, 1)
paramRequest["requestId"] = requestId
resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Network.getResponseBody", Params: paramRequest})
if err != nil {
return "", false, err
}
var chromeData struct {
Result struct {
Body string
Base64Encoded bool
}
}
if resp == nil {
return "", false, &gcdmessage.ChromeEmptyResponseErr{}
}
// test if error first
cerr := &gcdmessage.ChromeErrorResponse{}
json.Unmarshal(resp.Data, cerr)
if cerr != nil && cerr.Error != nil {
return "", false, &gcdmessage.ChromeRequestErr{Resp: cerr}
}
if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
return "", false, err
}
return chromeData.Result.Body, chromeData.Result.Base64Encoded, nil
}
示例14: AssociateUcsProfileToBlade
// associate a profile to a blade
func (s *UCSService) AssociateUcsProfileToBlade(p *AssociateUcsProfileToBladeParams) (*AssociateUcsProfileToBladeResponse, error) {
resp, err := s.cs.newRequest("associateUcsProfileToBlade", p.toURLValues())
if err != nil {
return nil, err
}
var r AssociateUcsProfileToBladeResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, warn, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
return nil, err
}
// If 'warn' has a value it means the job is running longer than the configured
// timeout, the resonse will contain the jobid of the running async job
if warn != nil {
return &r, warn
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
示例15: TestBool
func (testSuite *BoolTest) TestBool(c *C) {
inputBuf := `{"B": true, "C": false, "D": {"Ref": "foo"}, "E": "true"}`
v := struct {
A *BoolExpr `json:",omitempty"`
B *BoolExpr `json:",omitempty"`
C *BoolExpr `json:",omitempty"`
D *BoolExpr `json:",omitempty"`
E *BoolExpr `json:",omitempty"`
}{}
err := json.Unmarshal([]byte(inputBuf), &v)
c.Assert(err, IsNil)
c.Assert(v.A, IsNil)
c.Assert(v.B, DeepEquals, Bool(true))
c.Assert(v.C, DeepEquals, Bool(false))
c.Assert(v.D, DeepEquals, Ref("foo").Bool())
c.Assert(v.E, DeepEquals, Bool(true))
buf, err := json.Marshal(v)
c.Assert(err, IsNil)
c.Assert(string(buf), Equals,
`{"B":true,"C":false,"D":{"Ref":"foo"},"E":true}`)
inputBuf = `{"A": "invalid"}`
err = json.Unmarshal([]byte(inputBuf), &v)
c.Assert(err, ErrorMatches, "json: cannot unmarshal string into Go value of type bool")
inputBuf = `{"A": {"Fn::Missing": "invalid"}}`
err = json.Unmarshal([]byte(inputBuf), &v)
c.Assert(err, ErrorMatches, "unknown function Fn::Missing")
}