import ( "fmt" "github.com/hyperledger/fabric/core/chaincode/shim" ) func (c *MyChaincode) MyFunction(stub shim.ChaincodeStubInterface) pb.Response { key := "myKey" value := []byte("myValue") err := stub.PutState(key, value) if err != nil { return shim.Error(fmt.Sprintf("Failed to put state. Error: %s", err.Error())) } return shim.Success(nil) }
import ( "encoding/json" "github.com/hyperledger/fabric/core/chaincode/shim" ) type myObject struct { Name string `json:"name"` Value int `json:"value"` } func (c *MyChaincode) MyFunction(stub shim.ChaincodeStubInterface) pb.Response { key := "myKey" myObj := myObject{Name: "myName", Value: 123} value, err := json.Marshal(myObj) if err != nil { return shim.Error(fmt.Sprintf("Failed to marshal object. Error: %s", err.Error())) } err = stub.PutState(key, value) if err != nil { return shim.Error(fmt.Sprintf("Failed to put state. Error: %s", err.Error())) } return shim.Success(nil) }This example demonstrates how to store a JSON-formatted object in the state database using the PutState function. The function creates an instance of the "myObject" struct and serializes it into a JSON byte array using the "encoding/json" package. The resulting byte array is then passed to the PutState function along with a key to store the data in the state database.