当前位置: 首页>>代码示例>>Golang>>正文


Golang yaml.ToJSON函数代码示例

本文整理汇总了Golang中k8s/io/kubernetes/pkg/util/yaml.ToJSON函数的典型用法代码示例。如果您正苦于以下问题:Golang ToJSON函数的具体用法?Golang ToJSON怎么用?Golang ToJSON使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ToJSON函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: RunEdit

func RunEdit(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, filenames []string) error {
	addSource := func(b *resource.Builder, enforceNamespace bool, printer kubectl.ResourcePrinter) *resource.Builder {
		return b.FilenameParam(enforceNamespace, filenames...).
			ResourceTypeOrNameArgs(true, args...).
			Latest()
	}

	process := func(visitor resource.Visitor, original, edited []byte, obj runtime.Object, updates *resource.Info, file string, results *editResults, mapper meta.RESTMapper, defaultVersion string) error {
		// use strategic merge to create a patch
		originalJS, err := yaml.ToJSON(original)
		if err != nil {
			return preservedFile(err, file, out)
		}
		editedJS, err := yaml.ToJSON(edited)
		if err != nil {
			return preservedFile(err, file, out)
		}
		patch, err := strategicpatch.CreateStrategicMergePatch(originalJS, editedJS, obj)
		// TODO: change all jsonmerge to strategicpatch
		// for checking preconditions
		preconditions := []jsonmerge.PreconditionFunc{}
		if err != nil {
			glog.V(4).Infof("Unable to calculate diff, no merge is possible: %v", err)
			return preservedFile(err, file, out)
		} else {
			preconditions = append(preconditions, jsonmerge.RequireKeyUnchanged("apiVersion"))
			preconditions = append(preconditions, jsonmerge.RequireKeyUnchanged("kind"))
			preconditions = append(preconditions, jsonmerge.RequireMetadataKeyUnchanged("name"))
			results.version = defaultVersion
		}

		if hold, msg := jsonmerge.TestPreconditionsHold(patch, preconditions); !hold {
			fmt.Fprintf(out, "error: %s", msg)
			return preservedFile(nil, file, out)
		}

		return visitor.Visit(func(info *resource.Info, err error) error {
			patched, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch)
			if err != nil {
				fmt.Fprintln(out, results.addError(err, info))
				return nil
			}
			info.Refresh(patched, true)
			cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, "edited")
			return nil
		})
	}

	return doEdit(f, out, cmd, "kubectl-edit-", true, addSource, process)
}
开发者ID:DirectXMan12,项目名称:kubernetes,代码行数:50,代码来源:edit.go

示例2: CreateRc

func (conf *K8sClientConfig) CreateRc(fileName string) (rc *api.ReplicationController, err error) {
	if conf.client == nil {
		conf.Init()
	}
	if !strings.HasSuffix(fileName, ".yaml") && !strings.HasSuffix(fileName, ".json") {
		err = fmt.Errorf("Only Support Yaml and Json")
		return
	}
	data, err := ioutil.ReadFile(fileName)
	if err != nil {
		log.Fatalf("Unexpected error while reading file: %v", err)
		return
	}
	jsonData := data
	if strings.HasSuffix(fileName, ".yaml") {
		jsonData, err = yaml.ToJSON(data)
		if err != nil {
			log.Fatalf("Unexpected error while changing Yaml to Json: %v", err)
			return
		}
	}
	//log.Println(string(jsonData))
	ctrl := &api.ReplicationController{}
	if err = runtime.DecodeInto(api.Codecs.LegacyCodec(apiunversioned.GroupVersion{}), jsonData, ctrl); err != nil {
		log.Fatalf("Unexpected error decoding rc: %v", err)
	}
	//log.Println(ctrl.Spec.Template.)
	rc, err = conf.createReplicationControllers(ctrl)
	return
}
开发者ID:tangfeixiong,项目名称:go-to-kubernetes,代码行数:30,代码来源:client.go

示例3: registerAdmissionPlugins

func registerAdmissionPlugins(t *testing.T, names ...string) {
	for _, name := range names {
		pluginName := name
		admission.RegisterPlugin(pluginName, func(client kclientset.Interface, config io.Reader) (admission.Interface, error) {
			plugin := &testAdmissionPlugin{
				name: pluginName,
			}
			if config != nil && !reflect.ValueOf(config).IsNil() {
				configData, err := ioutil.ReadAll(config)
				if err != nil {
					return nil, err
				}
				configData, err = kyaml.ToJSON(configData)
				if err != nil {
					return nil, err
				}
				configObj := &TestPluginConfig{}
				err = runtime.DecodeInto(kapi.Codecs.UniversalDecoder(), configData, configObj)
				if err != nil {
					return nil, err
				}
				plugin.labelValue = configObj.Data
			}
			return plugin, nil
		})
	}
}
开发者ID:LalatenduMohanty,项目名称:origin,代码行数:27,代码来源:admissionconfig_test.go

示例4: Parse

// Parse takes a filename, loads the file, and parses it into one or more *Manifest objects.
func Parse(filename string) ([]*Manifest, error) {
	in, err := os.Open(filename)
	if err != nil {
		return nil, err
	}

	ms := []*Manifest{}

	docs, err := SplitYAML(in)
	in.Close()
	if err != nil {
		return ms, err
	}

	for _, doc := range docs {
		data, err := yaml.ToJSON(doc)
		if err != nil {
			return nil, fmt.Errorf("Failed to parse %s: %s", filename, err)
		}

		vo, version, kind, err := api.Scheme.Raw().DecodeToVersionedObject(data)
		if err != nil {
			return ms, err
		}

		m := &Manifest{Version: version, Kind: kind, VersionedObject: vo, Source: filename}
		ms = append(ms, m)
	}
	return ms, nil
}
开发者ID:prydonius,项目名称:helm-classic,代码行数:31,代码来源:manifest.go

示例5: tryDecodeSinglePod

func tryDecodeSinglePod(data []byte, defaultFn defaultFunc) (parsed bool, pod *api.Pod, err error) {
	// JSON is valid YAML, so this should work for everything.
	json, err := utilyaml.ToJSON(data)
	if err != nil {
		return false, nil, err
	}
	obj, err := api.Scheme.Decode(json)
	if err != nil {
		return false, pod, err
	}
	// Check whether the object could be converted to single pod.
	if _, ok := obj.(*api.Pod); !ok {
		err = fmt.Errorf("invalid pod: %+v", obj)
		return false, pod, err
	}
	newPod := obj.(*api.Pod)
	// Apply default values and validate the pod.
	if err = defaultFn(newPod); err != nil {
		return true, pod, err
	}
	if errs := validation.ValidatePod(newPod); len(errs) > 0 {
		err = fmt.Errorf("invalid pod: %v", errs)
		return true, pod, err
	}
	return true, newPod, nil
}
开发者ID:jojimt,项目名称:contrib,代码行数:26,代码来源:common.go

示例6: ValidateBytes

// TODO: Consider using a mocking library instead or fully fleshing this out into a fake impl and putting it in some
// generally available location
func (f *Factory) ValidateBytes(data []byte) error {
	var obj interface{}
	out, err := k8syaml.ToJSON(data)
	if err != nil {
		return err
	}
	data = out
	if err := json.Unmarshal(data, &obj); err != nil {
		return err
	}
	fields, ok := obj.(map[string]interface{})
	if !ok {
		return fmt.Errorf("error in unmarshaling data %s", string(data))
	}
	// Note: This only supports the 2 api versions we expect from the test it is currently supporting.
	groupVersion := fields["apiVersion"]
	switch groupVersion {
	case "v1":
		return f.defaultSchema.ValidateBytes(data)
	case "extensions/v1beta1":
		return f.extensionsSchema.ValidateBytes(data)
	default:
		return fmt.Errorf("Unsupported API version %s", groupVersion)
	}
}
开发者ID:RyanBinfeng,项目名称:kubernetes,代码行数:27,代码来源:schema_test.go

示例7: ReadObjectsFromPath

// ReadObjectsFromPath reads objects from the specified file for testing.
func ReadObjectsFromPath(path, namespace string, decoder runtime.Decoder, typer runtime.ObjectTyper) ([]runtime.Object, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	data, err = yaml.ToJSON(data)
	if err != nil {
		return nil, err
	}
	obj, err := runtime.Decode(decoder, data)
	if err != nil {
		return nil, err
	}
	if !meta.IsListType(obj) {
		if err := setNamespace(typer, obj, namespace); err != nil {
			return nil, err
		}
		return []runtime.Object{obj}, nil
	}
	list, err := meta.ExtractList(obj)
	if err != nil {
		return nil, err
	}
	errs := runtime.DecodeList(list, decoder)
	if len(errs) > 0 {
		return nil, errs[0]
	}
	for _, o := range list {
		if err := setNamespace(typer, o, namespace); err != nil {
			return nil, err
		}
	}
	return list, nil
}
开发者ID:LalatenduMohanty,项目名称:origin,代码行数:35,代码来源:fixture.go

示例8: walkJSONFiles

func walkJSONFiles(inDir string, fn func(name, path string, data []byte)) error {
	err := filepath.Walk(inDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() && path != inDir {
			return filepath.SkipDir
		}
		name := filepath.Base(path)
		ext := filepath.Ext(name)
		if ext != "" {
			name = name[:len(name)-len(ext)]
		}
		if !(ext == ".json" || ext == ".yaml") {
			return nil
		}
		glog.Infof("testing %s", path)
		data, err := ioutil.ReadFile(path)
		if err != nil {
			return err
		}
		if ext == ".yaml" {
			data, err = yaml.ToJSON(data)
			if err != nil {
				return err
			}
		}
		fn(name, path, data)
		return nil
	})
	return err
}
开发者ID:RomainVabre,项目名称:origin,代码行数:32,代码来源:examples_test.go

示例9: parseTokenCmdOutput

func (c *commandTokenSource) parseTokenCmdOutput(output []byte) (*oauth2.Token, error) {
	output, err := yaml.ToJSON(output)
	if err != nil {
		return nil, err
	}
	var data interface{}
	if err := json.Unmarshal(output, &data); err != nil {
		return nil, err
	}

	accessToken, err := parseJSONPath(data, "token-key", c.tokenKey)
	if err != nil {
		return nil, fmt.Errorf("error parsing token-key %q: %v", c.tokenKey, err)
	}
	expiryStr, err := parseJSONPath(data, "expiry-key", c.expiryKey)
	if err != nil {
		return nil, fmt.Errorf("error parsing expiry-key %q: %v", c.expiryKey, err)
	}
	var expiry time.Time
	if t, err := time.Parse(c.timeFmt, expiryStr); err != nil {
		glog.V(4).Infof("Failed to parse token expiry from %s (fmt=%s): %v", expiryStr, c.timeFmt, err)
	} else {
		expiry = t
	}

	return &oauth2.Token{
		AccessToken: accessToken,
		TokenType:   "Bearer",
		Expiry:      expiry,
	}, nil
}
开发者ID:eljefedelrodeodeljefe,项目名称:kubernetes,代码行数:31,代码来源:gcp.go

示例10: tryDecodePodList

func tryDecodePodList(data []byte, defaultFn defaultFunc) (parsed bool, pods api.PodList, err error) {
	json, err := utilyaml.ToJSON(data)
	if err != nil {
		return false, api.PodList{}, err
	}
	obj, err := api.Scheme.Decode(json)
	if err != nil {
		return false, pods, err
	}
	// Check whether the object could be converted to list of pods.
	if _, ok := obj.(*api.PodList); !ok {
		err = fmt.Errorf("invalid pods list: %+v", obj)
		return false, pods, err
	}
	newPods := obj.(*api.PodList)
	// Apply default values and validate pods.
	for i := range newPods.Items {
		newPod := &newPods.Items[i]
		if err = defaultFn(newPod); err != nil {
			return true, pods, err
		}
		if errs := validation.ValidatePod(newPod); len(errs) > 0 {
			err = fmt.Errorf("invalid pod: %v", errs)
			return true, pods, err
		}
	}
	return true, *newPods, err
}
开发者ID:jojimt,项目名称:contrib,代码行数:28,代码来源:common.go

示例11: stripComments

// stripComments will transform a YAML file into JSON, thus dropping any comments
// in it. Note that if the given file has a syntax error, the transformation will
// fail and we will manually drop all comments from the file.
func stripComments(file []byte) []byte {
	stripped, err := yaml.ToJSON(file)
	if err != nil {
		stripped = manualStrip(file)
	}
	return stripped
}
开发者ID:lohmander,项目名称:dashboard,代码行数:10,代码来源:edit.go

示例12: walkJSONFiles

func walkJSONFiles(inDir string, fn func(name, path string, data []byte)) error {
	return filepath.Walk(inDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if info.IsDir() && path != inDir {
			return filepath.SkipDir
		}

		file := filepath.Base(path)
		if ext := filepath.Ext(file); ext == ".json" || ext == ".yaml" {
			glog.Infof("Testing %s", path)
			data, err := ioutil.ReadFile(path)
			if err != nil {
				return err
			}
			name := strings.TrimSuffix(file, ext)

			if ext == ".yaml" {
				out, err := yaml.ToJSON(data)
				if err != nil {
					return fmt.Errorf("%s: %v", path, err)
				}
				data = out
			}

			fn(name, path, data)
		}
		return nil
	})
}
开发者ID:koori02,项目名称:kubernetes,代码行数:32,代码来源:examples_test.go

示例13: ValidateBytes

func (s *SwaggerSchema) ValidateBytes(data []byte) error {
	var obj interface{}
	out, err := yaml.ToJSON(data)
	if err != nil {
		return err
	}
	data = out
	if err := json.Unmarshal(data, &obj); err != nil {
		return err
	}
	fields, ok := obj.(map[string]interface{})
	if !ok {
		return fmt.Errorf("error in unmarshaling data %s", string(data))
	}
	apiVersion := fields["apiVersion"]
	if apiVersion == nil {
		return fmt.Errorf("apiVersion not set")
	}
	kind := fields["kind"]
	if kind == nil {
		return fmt.Errorf("kind not set")
	}
	allErrs := s.ValidateObject(obj, apiVersion.(string), "", apiVersion.(string)+"."+kind.(string))
	if len(allErrs) == 1 {
		return allErrs[0]
	}
	return errors.NewAggregate(allErrs)
}
开发者ID:naxhh,项目名称:heapster,代码行数:28,代码来源:schema.go

示例14: Apply

// Apply attempts to apply the changes described by Delta onto latest,
// returning an error if the changes cannot be applied cleanly.
// IsConflicting will be true if the changes overlap, otherwise a
// generic error will be returned.
func (d *Delta) Apply(latest []byte) ([]byte, error) {
	base, err := yaml.ToJSON(latest)
	if err != nil {
		return nil, err
	}
	changes, err := jsonpatch.CreateMergePatch(d.original, base)
	if err != nil {
		return nil, err
	}
	diff1 := make(map[string]interface{})
	if err := json.Unmarshal(d.edit, &diff1); err != nil {
		return nil, err
	}
	diff2 := make(map[string]interface{})
	if err := json.Unmarshal(changes, &diff2); err != nil {
		return nil, err
	}
	for _, fn := range d.preconditions {
		hold1, _ := fn(diff1)
		hold2, _ := fn(diff2)
		if !hold1 || !hold2 {
			return nil, ErrPreconditionFailed
		}
	}

	glog.V(6).Infof("Testing for conflict between:\n%s\n%s", string(d.edit), string(changes))
	if hasConflicts(diff1, diff2) {
		return nil, ErrConflict
	}
	return jsonpatch.MergePatch(base, d.edit)
}
开发者ID:previousnext,项目名称:kube-ingress,代码行数:35,代码来源:jsonmerge.go

示例15: Decode

func (c yamlCodec) Decode(data []byte) (Object, error) {
	out, err := yaml.ToJSON(data)
	if err != nil {
		return nil, err
	}
	data = out
	return c.Codec.Decode(data)
}
开发者ID:leonfs,项目名称:romulus,代码行数:8,代码来源:codec.go


注:本文中的k8s/io/kubernetes/pkg/util/yaml.ToJSON函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。