简体   繁体   English

如何在golang中替换/更新json数组中的键值?

[英]How to replace/update a key value inside a json array in golang?

I have a json array where it contains some flags as key and I have set the default values for those keys as false.我有一个 json 数组,其中包含一些作为键的标志,并且我已将这些键的默认值设置为 false。 this is my json array.这是我的 json 数组。

var flags = map[string]bool{
    "terminationFlag":  false,
    "transferFlag":   false,
    "jrCancelledFlag": false,
    "jrFilledFlag":  false,
}

On performing an operation in a for loop, i have to update 1 field in the above json array as true.在 for 循环中执行操作时,我必须将上述 json 数组中的 1 个字段更新为 true。 During the next iteration, it has to update the 2nd field in the json array as true.在下一次迭代期间,它必须将 json 数组中的第二个字段更新为 true。 After all the fields in the json array is set to true, I have to return the json array. json数组中的所有字段都设置为true后,我要返回json数组。

the code i tried:我试过的代码:

  Keystrings := []string{"terminationReport - 2019-1","transferReport - 2019-1","jrCancelledReport - 2019-1","jrFilledReport - 2019-1"}
  fmt.Println("Keystrings ", Keystrings)

  for i,value := range Keystrings {     
    bytesread, err = stub.GetState(value)
    var result []string
    _ = json.Unmarshal(bytesread, &result)
    fmt.Println("result ", result)
    if result[0] == "yes"{
        fmt.Println("result in if ", result)
       flags[i] = true
    }
}

Since it's very hard to understand from the question what is being asked, here's a simple attempt at working with similar data as the question, in the hope that you can take the right parts from this sample and adapt them to your issue.由于很难从问题中理解所问的是什么,这里有一个简单的尝试,尝试使用与问题类似的数据,希望您能从这个示例中获取正确的部分并使其适应您的问题。 Follow the comments in the code to understand what's going on.按照代码中的注释了解发生了什么。

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

var jsonBlob = []byte(`["jrCancelledFlag", "yes"]`)

var flags = map[string]bool{
    "terminationFlag": false,
    "transferFlag":    false,
    "jrCancelledFlag": false,
    "jrFilledFlag":    false,
}

func main() {
    // Parse jsonBlob into a slice of strings
    var parsed []string
    if err := json.Unmarshal(jsonBlob, &parsed); err != nil {
        log.Fatalf("JSON unmarshal: %s", err)
    }

    // Expect the slice to be of length 2, first item flag name, second item
    // yes/no.
    if len(parsed) != 2 {
        log.Fatalf("parsed len %d, expected 2", len(parsed))
    }

    // Assume parsed[0] actually appears in flags... otherwise more error checking
    // is needed.
    if parsed[1] == "yes" {
        flags[parsed[0]] = true
    }

    // Emit updated flags as json
    json, err := json.Marshal(flags)
    if err != nil {
        log.Fatalf("JSON marshal: %s", err)
    }
    fmt.Println(string(json))
}

This can be achieved cleaning by using the JSON interface to define your own unmarshaller这可以通过使用 JSON 接口定义自己的解组器来实现清理

https://medium.com/@nate510/dynamic-json-umarshalling-in-go-88095561d6a0 https://medium.com/@nate510/dynamic-json-umarshalling-in-go-88095561d6a0

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

var jsonBlob = []byte(`["jrCancelledFlag", "yes"]`)

// Flags ...
type Flags struct {
    TerminationFlag bool `json:"terminationFlag,omitempty"`
    TransferFlag    bool `json:"transferFlag,omitempty"`
    JRCancelledFlag bool `json:"jrCancelledFlag,omitempty"`
    JRFilledFlag    bool `json:"jrFilledFlag,omitempty"`
}

// UnmarshalJSON satisfies the JSON unmarshaller interface
func (f *Flags) UnmarshalJSON(data []byte) error {
    var parsed []string
    if err := json.Unmarshal(jsonBlob, &parsed); err != nil {
        return err
    }
    if len(parsed)%2 != 0 {
        return fmt.Errorf("expected string to be evenly paired")
    }

    for i := 0; i < len(parsed); i++ {
        j := i + 1
        if j < len(parsed) {
            switch parsed[i] {
            case "terminationFlag":
                f.TerminationFlag = toBool(parsed[j])
            case "transferFlag":
                f.TransferFlag = toBool(parsed[j])
            case "jrCancelledFlag":
                f.JRCancelledFlag = toBool(parsed[j])
            case "jrFilledFlag":
                f.JRFilledFlag = toBool(parsed[j])
            }
        }
    }
    return nil
}

func toBool(s string) bool {
    if s == "yes" {
        return true
    }
    return false
}

func main() {

    var flags Flags
    err := json.Unmarshal(jsonBlob, &flags)
    if err != nil {
        log.Fatal(err)
    }

    b, _ := json.Marshal(flags)
    fmt.Println(string(b))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM