removing \n \r\n from json in go lang - json

The program reads the file from input json,then appends extra structure within the program. I have everything working but when i printout in my console it has extra n\ r and spaces in the json. In the playground it doesnt but when i run it from shell it does. The problem how can i removed to match the outcome file.
File thats getting inputted:
{
"mac_address": "",
"serial_number": "4UW1234",
"device_type": "STORuhaiul",
"device_model": "N9ZsdfsdA",
"part_number": "N9sdfsdfsdf5A",
"extra_attributes": [
{
"attribute_type": "ENTITLEMENT_ID",
"attribute_value": "ABC123JKJUBCDZ"
}
],
"platform_customer_id": "f850243a4c1911eca07f6db9a",
"application_customer_id": "88e0ff88c07811ed76c7988eb"
}
Outcome file should be like this exactly quoted(result)
{
"specversion": "1.0",
"id": "ce20b92d-b45b7-a544-8fe4d8f7ff06",
"source": "CCS",
"type": "",
"time": "2022-08-09T23:59:08.468903+00:00",
"data": "{\"mac_address\": null, \"serial_number\": \"ADL-DHCI1\", \"device_type\": \"DHCI_STORAGE\", \"device_model\": \"NIMBLE DHCI STORAGE\", \"part_number\": \"60\", \"extra_attributes\": [
{\"attribute_type\": \"ENTITLEMENT_ID\", \"attribute_value\": \"YIZUYYNEYV0LVAU\"}
], \"tag_entities\": [], \"platform_customer_id\": \"a07db1081d5b41eeed59645ee95\", \"application_customer_id\": \"3118643e201cb2c92e8b7aa93178\", \"folder_name\": null}"
}
my code
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"time"
"github.com/google/uuid"
)
type Event struct {
Specversion string `json:"specversion"`
ID uuid.UUID `json:"id"` /// uuid
Source string `json:"source"`
Type string `json:"type"`
Time time.Time `json:"time"`
Data string `json:"data"` /// this part supposed to come from the file
}
type Data struct {
MacAddress string `json:"mac_address"`
SerialNumber string `json:"serial_number"`
DeviceType string `json:"device_type"`
DeviceModel string `json:"device_model"`
PartNumber string `json:"part_number"`
ExtraAttributes []DeviceAttribute `json:"extra_attributes"`
PlatformCustomerID string `json:"platform_customer_id"`
ApplicationCustomerID string `json:"application_customer_id"`
}
type DeviceAttribute struct {
AttributeType string `json:"attribute_type"`
AttributeValue string `json:"attribute_value"`
}
func main() {
if len(os.Args) < 1 { //checking for provided argument if the first arg satisfy then use read file
fmt.Println("Usage : " + os.Args[0] + " file name")
help()
os.Exit(1)
}
Data, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println("Cannot read the file or file does not exists")
os.Exit(1)
}
e := Event{
Specversion: "1.0",
ID: uuid.New(),
Source: "CSS",
Type: "", // user input -p or -u,
Time: time.Now(),
Data: string(Data),
}
out, _ := json.Marshal(e)
fmt.Println(string(out))
}
func help() {
fmt.Println("help")
}
When im running the program im getting this output from vs code
{"specversion":"1.0","id":"c053519-71ef-4a80-a47b-392ac2434f99","source":"CSS","type":"","time":"2022-09-09T14:01:40.2599627-05:00","data":"{\r\n \"mac_address\": \"\",\r\n \"serial_number\": \"4UW1234\",\r\n \"device_type\": \"STOuhaul\",\r\n \"device_model\": \"N95A\",\r\n \"part_number\": \"N9Z55A\",\r\n \"extra_attributes\": [\r\n {\r\n \"attribute_type\": \"ENTITLEMENT_ID\",\r\n \"attribute_value\": \"ABC123JV9UBCDZ\"\r\n }\r\n ],\r\n \"platform_cust.....
output from shell
{"specversion":"1.0","id":"5f5b1841-d99c-4eef-8867-7c09a23d5bb5","source":"CSS","type":"","time":"2022-09-09T19:34:43.802856511Z","data":" \"mac_address\": \"\",\n \"serial_number\": \"j\",\n \"device_type\": \"STORAGE\",\n \"device_model\": \"VIRTUAL\",\n \"part_number\": \"VIRTUAL\",\n \"extra_attributes\": [\n {\n \"attribute_type\": \"ENTITLEMENT_ID\",\n \"attribute_value\": \"H6MI9JYNJCOSBL1GTjfgjfjY6P\"\n }\n ],\n \"platform_customer_id\": \"b050fa3a49hfghfghfbbf0a2a9c6414efb\",\n \"application_customer_id\": \"03eda3027f4c11ec8cee12749a9c9018\"\n\n"}
go playcode

Use the following code to remove carriage return and line feed from json:
replacer := strings.NewReplacer("\r", "", "\n", "")
Data = []byte(replacer.Replace(string(Data)))
https://go.dev/play/p/0bDpGqybskL

Related

inputting json file from shell i converted using marshal the file but now i have to add metadata uuid and time

Im inputing JSON file from shell and converting to specific format i did that part on bottom but im trying to include like metadat like time ,uuid and couple of other thing to it then printout the new json file.My issue i cant put the new info to data part of the data
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"time"
// "github.com/google/uuid"
)
func help() {
fmt.Println("help")
}
type Event struct{
Specversion string `json:"specversion"`
ID string `json:"id"` /// uuid
Source string `json:"source"`
// Type bool `json:"type"`
Time time.Now `json:"time"`
Data string `json:"data"` /// this part supposed to come from the file
}
func main(){
if len(os.Args) < 1 { //checking for provided argument if the first arg satisfy then use read file
fmt.Println("Usage : " + os.Args[0] + " file name")
help()
os.Exit(1)
}
file, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println("Cannot read the file or file does not exists")
os.Exit(1)
}
out, err := json.Marshal(map[string]string{"data": string(file)})
if err != nil {
panic(err)
}
//fmt.Println(string(out))
e := Event{
Specversion: "1.0",
//id: uuid.New(),
Source: "CSS",
//type: true,
Time: time.Now(),
Data: data.(string),
}
fmt.Println(string(out))
fmt.Println(string(e))
//fmt.Println(string(id))
}
The outcome should be this
{
"specversion": "1.0",
"id": "ce20b92d-b45b-hhd7-a544-8fe4d8f7ff06",
"source": "CCS",
"type": "EVENT",
"time": "2022-08-09T23:59:08.468903+00:00",
"data": "{\"mac_address\": null, \".................
original file from input
"mac_address": "",
"serial_number": "j",
"device_type": "STORAGE",
"device_model": "VIRTUAL",
"part_number": "VIRTUAL",
"extra_attributes": [
{
"attribute_type": "ENTITLEMENT_ID",
"attribute_value": "H6MI9JYNJCOSBL1GTjfgjfjY6P"
The application marshals a map with the data, but not the metadata. The application configures a value with the metadata and data, but does nothing with it. Pull those pieces together. Something like this:
file, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println("Cannot read the file or file does not exists")
os.Exit(1)
}
e := Event{
Specversion: "1.0",
Source: "CSS",
Time: time.Now(),
Data: string(file),
}
out, _ := json.MarshalIndent(e, "", " ")
fmt.Println(string(out))
Run the program on the playground.
You can try the approach below for this:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"time"
// "github.com/google/uuid"
)
func help() {
fmt.Println("help")
}
type Event struct {
Specversion string `json:"specversion"`
ID string `json:"id"` /// uuid
Source string `json:"source"`
// Type bool `json:"type"`
Time time.Now `json:"time"`
Data map[string]interface{} `json:"data"` /// this part supposed to come from the file
}
func main() {
if len(os.Args) < 1 { //checking for provided argument if the first arg satisfy then use read file
fmt.Println("Usage : " + os.Args[0] + " file name")
help()
os.Exit(1)
}
file, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println("Cannot read the file or file does not exists")
os.Exit(1)
}
res := map[string]interface{}{}
err = json.Unmarshal(file, &res)
if err != nil {
panic(err)
}
e := Event{
Specversion: "1.0",
//id: uuid.New(),
Source: "CSS",
//type: true,
Time: time.Now(),
Data: res,
}
fmt.Println(e)
}
Defining your Event struct data type as map sting interface helps.
Hope this works.

Encoding struct to json Go

I have an issue encoding struct to json my code is
type MainStructure struct {
Text string json:"text,omitempty"
Array []TestArray json:"test_array,omitmepty"
}
type TestArray struct {
ArrayText string json:"array_text,omitempty"
}
func main() {
Test := MainStructure{
Text: "test",
Array: [
{
ArrayText: "test1"
},
{
ArrayText: "test2"
}
]
}
body := new(bytes.Buffer)
json.NewEncoder(body).Encode(&Test)
fmt.Println(string([]byte(body)))
}
the wanted result should be
{
"text": "test",
"test_array": [
{
"array_text": "test1"
},
{
"array_text": "test2"
}
]
}
I do not mind if it's "Marshal" or "encoding/json"
To encode a struct to JSON string, there are three ways that provided by standard library :
Using Encoder which convert struct to JSON string, then write it to io.Writer. This one usually used if you want to send JSON data as HTTP request, or saving the JSON string to a file.
Using Marshal which simply convert struct to bytes, which can be easily converted to string.
Using MarshalIndent which works like Marshal, except it's also prettify the output. This is what you want for your problem right now.
To compare between those three methods, you can use this code (Go Playground):
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type MainStructure struct {
Text string `json:"text,omitempty"`
Array []TestArray `json:"test_array,omitempty"`
}
type TestArray struct {
ArrayText string `json:"array_text,omitempty"`
}
func main() {
Test := MainStructure{
Text: "test",
Array: []TestArray{
{ArrayText: "test1"},
{ArrayText: "test2"},
},
}
// Using marshal indent
btResult, _ := json.MarshalIndent(&Test, "", " ")
fmt.Println("Using Marshal Indent:\n" + string(btResult))
// Using marshal
btResult, _ = json.Marshal(&Test)
fmt.Println("\nUsing Marshal:\n" + string(btResult))
// Using encoder
var buffer bytes.Buffer
json.NewEncoder(&buffer).Encode(&Test)
fmt.Println("\nUsing Encoder:\n" + buffer.String())
}
The output will look like this :
Using Marshal Indent:
{
"text": "test",
"test_array": [
{
"array_text": "test1"
},
{
"array_text": "test2"
}
]
}
Using Marshal:
{"text":"test","test_array":[{"array_text":"test1"},{"array_text":"test2"}]}
Using Encoder:
{"text":"test","test_array":[{"array_text":"test1"},{"array_text":"test2"}]}
First of all I think you are going wrong on how to create a struct in go, as you can easily convert them to json.
You should be first making a proper struct then do json.marshal(Test) to convert it to proper json like:
package main
import (
"encoding/json"
"fmt"
)
func main() {
type TestArray struct {
ArrayText string `json:"array_text,omitempty"`
}
type MainStructure struct {
Text string `json:"text,omitempty"`
Array []TestArray `json:"test_array,omitmepty"`
}
Test := MainStructure{
Text: "test",
Array: []TestArray{
TestArray{ArrayText: "test1"},
TestArray{ArrayText: "test2"},
}}
bytes, err := json.Marshal(Test)
if err != nil {
fmt.Println("eror marshalling")
} else {
fmt.Println(string(bytes))
}
}
Check this out on play.golang.org
I could not get the point you wanted to use bytes.Buffer if your objective is just to put the result into the console. Assuming the point is:
Create a struct instance (corresponding to a JSON object)
Emit it in the screen
The following code can help you:
package main
import "encoding/json"
import "fmt"
type MainStructure struct {
Text string `json:"text,omitempty"`
Array []TestArray `json:"test_array,omitmepty"`
}
type TestArray struct {
ArrayText string `json:"array_text,omitempty"`
}
func main() {
Test := MainStructure{
Text: "test",
Array: []TestArray{
TestArray{"test1"},
TestArray{"test2"},
},
}
res, _ := json.MarshalIndent(Test, "", "\t")
fmt.Println(string(res))
}
json.MarshalIndent is used to make result pretty-formatted, if you bother it.

Golang parse JSON with unknown keys [duplicate]

This question already has answers here:
How to unmarshal JSON with unknown fieldnames to struct [duplicate]
(1 answer)
Partly JSON unmarshal into a map in Go
(3 answers)
Unmarshal JSON with some known, and some unknown field names
(8 answers)
Closed 3 years ago.
I'm trying to unmarshal json with dynamic field keys to the struct
That json returned from storcli utility for linux.
One part of the code work well, but if json data contains many structs I can't unmarshal it.
I think that is because DriveDetailedInformation struct do not have all json tags.
Can anybody help me?
package main
import (
"fmt"
"encoding/json"
)
type jsonStruct struct {
Controllers []struct {
CommandStatus struct {
Controller int `json:"Controller"`
Status string `json:"Status"`
Description string `json:"Description"`
} `json:"Command Status"`
ResponseData map[string]*json.RawMessage `json:"Response Data"`
} `json:"Controllers"`
}
type DriveStruct struct {
EIDSlt string `json:"EID:Slt"`
DID int `json:"DID"`
State string `json:"State"`
DG int `json:"DG"`
Size string `json:"Size"`
Intf string `json:"Intf"`
Med string `json:"Med"`
SED string `json:"SED"`
PI string `json:"PI"`
SeSz string `json:"SeSz"`
Model string `json:"Model"`
Sp string `json:"Sp"`
}
type DriveDetailedInformation struct {
DriveState map[string]DriveStateStruct
DriveDeviceAttributes map[string]DriveDeviceAttributesStruct
DrivePoliciesSettings map[string]DrivePoliciesSettingsStruct
InquiryData string `json:"Inquiry Data"`
}
type DriveStateStruct struct {
ShieldCounter int `json:"Shield Counter"`
MediaErrorCount int `json:"Media Error Count"`
OtherErrorCount int `json:"Other Error Count"`
BBMErrorCount int `json:"BBM Error Count"`
DriveTemperature string `json:"Drive Temperature"`
PredictiveFailureCount int `json:"Predictive Failure Count"`
SMARTAlertFlaggedByDrive string `json:"S.M.A.R.T alert flagged by drive"`
}
type DriveDeviceAttributesStruct struct {
SN string `json:"SN"`
ManufacturerID string `json:"Manufacturer Id"`
ModelNumber string `json:"Model Number"`
NANDVendor string `json:"NAND Vendor"`
WWN string `json:"WWN"`
FirmwareRevision string `json:"Firmware Revision"`
RawSize string `json:"Raw size"`
CoercedSize string `json:"Coerced size"`
NonCoercedSize string `json:"Non Coerced size"`
DeviceSpeed string `json:"Device Speed"`
LinkSpeed string `json:"Link Speed"`
NCQSetting string `json:"NCQ setting"`
WriteCache string `json:"Write cache"`
SectorSize string `json:"Sector Size"`
ConnectorName string `json:"Connector Name"`
}
type DrivePoliciesSettingsStruct struct {
DrivePosition string `json:"Drive position"`
EnclosurePosition int `json:"Enclosure position"`
ConnectedPortNumber string `json:"Connected Port Number"`
SequenceNumber int `json:"Sequence Number"`
CommissionedSpare string `json:"Commissioned Spare"`
EmergencySpare string `json:"Emergency Spare"`
LastPredictiveFailureEventSequenceNumber int `json:"Last Predictive Failure Event Sequence Number"`
SuccessfulDiagnosticsCompletionOn string `json:"Successful diagnostics completion on"`
SEDCapable string `json:"SED Capable"`
SEDEnabled string `json:"SED Enabled"`
Secured string `json:"Secured"`
Locked string `json:"Locked"`
NeedsEKMAttention string `json:"Needs EKM Attention"`
PIEligible string `json:"PI Eligible"`
Certified string `json:"Certified"`
WidePortCapable string `json:"Wide Port Capable"`
PortInformation []struct {
Port int `json:"Port"`
Status string `json:"Status"`
Linkspeed string `json:"Linkspeed"`
SASAddress string `json:"SAS address"`
} `json:"Port Information"`
}
var jsonData = `
{
"Controllers":[
{
"Command Status":{
"Controller":0,
"Status":"Success",
"Description":"Show Drive Information Succeeded."
},
"Response Data":{
"Drive /c0/e31/s0":[
{
"EID:Slt":"31:0",
"DID":19,
"State":"Onln",
"DG":0,
"Size":"9.094 TB",
"Intf":"SATA",
"Med":"HDD",
"SED":"N",
"PI":"N",
"SeSz":"512B",
"Model":"ST10000DM0004-1ZC101",
"Sp":"U"
}
],
"Drive /c0/e31/s0 - Detailed Information":{
"Drive /c0/e31/s0 State":{
"Shield Counter":0,
"Media Error Count":0,
"Other Error Count":0,
"BBM Error Count":0,
"Drive Temperature":" 25C (77.00 F)",
"Predictive Failure Count":0,
"S.M.A.R.T alert flagged by drive":"No"
},
"Drive /c0/e31/s0 Device attributes":{
"SN":" ZA23V0DH",
"Manufacturer Id":"ATA ",
"Model Number":"ST10000DM0004-1ZC101",
"NAND Vendor":"NA",
"WWN":"5000c500a5ad06b6",
"Firmware Revision":"DN01 ",
"Raw size":"9.095 TB [0x48c400000 Sectors]",
"Coerced size":"9.094 TB [0x48c300000 Sectors]",
"Non Coerced size":"9.094 TB [0x48c300000 Sectors]",
"Device Speed":"6.0Gb/s",
"Link Speed":"6.0Gb/s",
"NCQ setting":"N/A",
"Write cache":"N/A",
"Sector Size":"512B",
"Connector Name":""
},
"Drive /c0/e31/s0 Policies/Settings":{
"Drive position":"DriveGroup:0, Span:0, Row:0",
"Enclosure position":0,
"Connected Port Number":"0(path0) ",
"Sequence Number":2,
"Commissioned Spare":"No",
"Emergency Spare":"No",
"Last Predictive Failure Event Sequence Number":0,
"Successful diagnostics completion on":"N/A",
"SED Capable":"No",
"SED Enabled":"No",
"Secured":"No",
"Locked":"No",
"Needs EKM Attention":"No",
"PI Eligible":"No",
"Certified":"No",
"Wide Port Capable":"No",
"Port Information":[
{
"Port":0,
"Status":"Active",
"Linkspeed":"6.0Gb/s",
"SAS address":"0x5003048001927c6c"
}
]
},
"Inquiry Data":""
},
"Drive /c0/e31/s1":[
{
"EID:Slt":"31:1",
"DID":20,
"State":"Onln",
"DG":0,
"Size":"9.094 TB",
"Intf":"SATA",
"Med":"HDD",
"SED":"N",
"PI":"N",
"SeSz":"512B",
"Model":"ST10000DM0004-1ZC101",
"Sp":"U"
}
],
"Drive /c0/e31/s1 - Detailed Information":{
"Drive /c0/e31/s1 State":{
"Shield Counter":0,
"Media Error Count":0,
"Other Error Count":0,
"BBM Error Count":0,
"Drive Temperature":" 25C (77.00 F)",
"Predictive Failure Count":0,
"S.M.A.R.T alert flagged by drive":"No"
},
"Drive /c0/e31/s1 Device attributes":{
"SN":" ZA23MCVS",
"Manufacturer Id":"ATA ",
"Model Number":"ST10000DM0004-1ZC101",
"NAND Vendor":"NA",
"WWN":"5000c500a5acc582",
"Firmware Revision":"DN01 ",
"Raw size":"9.095 TB [0x48c400000 Sectors]",
"Coerced size":"9.094 TB [0x48c300000 Sectors]",
"Non Coerced size":"9.094 TB [0x48c300000 Sectors]",
"Device Speed":"6.0Gb/s",
"Link Speed":"6.0Gb/s",
"NCQ setting":"N/A",
"Write cache":"N/A",
"Sector Size":"512B",
"Connector Name":""
},
"Drive /c0/e31/s1 Policies/Settings":{
"Drive position":"DriveGroup:0, Span:0, Row:1",
"Enclosure position":0,
"Connected Port Number":"0(path0) ",
"Sequence Number":2,
"Commissioned Spare":"No",
"Emergency Spare":"No",
"Last Predictive Failure Event Sequence Number":0,
"Successful diagnostics completion on":"N/A",
"SED Capable":"No",
"SED Enabled":"No",
"Secured":"No",
"Locked":"No",
"Needs EKM Attention":"No",
"PI Eligible":"No",
"Certified":"No",
"Wide Port Capable":"No",
"Port Information":[
{
"Port":0,
"Status":"Active",
"Linkspeed":"6.0Gb/s",
"SAS address":"0x5003048001927c6d"
}
]
},
"Inquiry Data":""
}
}
}
]
}
`
func main() {
var f jsonStruct
err := json.Unmarshal([]byte(jsonData), &f)
if err != nil {
fmt.Println("Error parsing JSON: ", err)
}
for _, controller := range f.Controllers {
for k, v := range controller.ResponseData {
///THAT IS WORK
var ds []DriveStruct
if err := json.Unmarshal(*v, &ds); err == nil {
fmt.Println(k, ds)
}
///THAT IS NOT WORK WHY?
var dds DriveDetailedInformation
if err := json.Unmarshal(*v, &dds); err == nil {
fmt.Println(k, dds)
}
}
}
}
Because your key value is not correct. Below is the code I modified.
type DriveDetailedInformation struct {
DriveState DriveStateStruct `json:"Drive /c0/e31/s0 State"`
DriveDeviceAttributes DriveDeviceAttributesStruct `json:"Drive /c0/e31/s0 Device attributes"`
DrivePoliciesSettings DrivePoliciesSettingsStruct `json:"Drive /c0/e31/s0 Policies/Settings"`
InquiryData string `json:"Inquiry Data"`
}
type DriveDetailedInformation1 struct {
DriveState DriveStateStruct `json:"Drive /c0/e31/s1 State"`
DriveDeviceAttributes DriveDeviceAttributesStruct `json:"Drive /c0/e31/s1 Device attributes"`
DrivePoliciesSettings DrivePoliciesSettingsStruct `json:"Drive /c0/e31/s1 Policies/Settings"`
InquiryData string `json:"Inquiry Data"`
}
func main() {
var f jsonStruct
err := json.Unmarshal([]byte(jsonData), &f)
if err != nil {
fmt.Println("Error parsing JSON: ", err)
}
for _, controller := range f.Controllers {
for k, v := range controller.ResponseData {
switch k {
case "Drive /c0/e31/s0","Drive /c0/e31/s1":
var ds []DriveStruct
if err := json.Unmarshal(*v, &ds); err == nil {
fmt.Println(k, ds)
}
case "Drive /c0/e31/s1 - Detailed Information":
var dds1 DriveDetailedInformation1
if err := json.Unmarshal(*v, &dds1); err == nil {
fmt.Println(k, dds1)
}
case "Drive /c0/e31/s0 - Detailed Information":
var dds DriveDetailedInformation
if err := json.Unmarshal(*v, &dds); err == nil {
fmt.Println(k, dds)
}
}
}
}
}
I think Response Data can be parsed in a structure.

Manually read JSON values

In Go I usually unmarshal my JSON into a struct and read values from the struct.. it works very well.
This time around I am only concerned with a certain element of a JSON object and because the overall JSON object is very large, I don't want to have to create a struct.
Is there a way in Go so that I can lookup values in the JSON object using keys or iterate arrays as per usual.
Considering the following JSON how could I pull out the title field only.
{
"title": "Found a bug",
"body": "I'm having a problem with this.",
"assignee": "octocat",
"milestone": 1,
"labels": [
"bug"
]
}
Dont declare fields you dont want.
https://play.golang.org/p/cQeMkUCyFy
package main
import (
"fmt"
"encoding/json"
)
type Struct struct {
Title string `json:"title"`
}
func main() {
test := `{
"title": "Found a bug",
"body": "I'm having a problem with this.",
"assignee": "octocat",
"milestone": 1,
"labels": [
"bug"
]
}`
var s Struct
json.Unmarshal([]byte(test), &s)
fmt.Printf("%#v", s)
}
Or if you want to completely get rid of structs:
var i interface{}
json.Unmarshal([]byte(test), &i)
fmt.Printf("%#v\n", i)
fmt.Println(i.(map[string]interface{})["title"].(string))
Or. It will swallow all conversion errors.
m := make(map[string]string)
json.Unmarshal([]byte(test), interface{}(&m))
fmt.Printf("%#v\n", m)
fmt.Println(m["title"])
To extend Darigaaz's answer, you can also use an anonymous struct declared within the parsing function. This avoids having to have package-level type declarations litter the code for single-use cases.
https://play.golang.org/p/MkOo1KNVbs
package main
import (
"encoding/json"
"fmt"
)
func main() {
test := `{
"title": "Found a bug",
"body": "I'm having a problem with this.",
"assignee": "octocat",
"milestone": 1,
"labels": [
"bug"
]
}`
var s struct {
Title string `json:"title"`
}
json.Unmarshal([]byte(test), &s)
fmt.Printf("%#v", s)
}
Check out go-simplejson
Example:
js, err := simplejson.NewJson([]byte(`{
"test": {
"string_array": ["asdf", "ghjk", "zxcv"],
"string_array_null": ["abc", null, "efg"],
"array": [1, "2", 3],
"arraywithsubs": [{"subkeyone": 1},
{"subkeytwo": 2, "subkeythree": 3}],
"int": 10,
"float": 5.150,
"string": "simplejson",
"bool": true,
"sub_obj": {"a": 1}
}
}`))
if _, ok = js.CheckGet("test"); !ok {
// Missing test struct
}
aws := js.Get("test").Get("arraywithsubs")
aws.GetIndex(0)
package main
import (
"encoding/json"
"fmt"
)
type Seller struct {
Name string
ShareName string
Holdings int
Quantity int
PerShare float64
}
type Buyer struct {
Name string
ShareName string
Holdings int
Quantity int
PerShare float64
}
func validateTransaction(seller Seller,buyer Buyer) bool{
var isallowTransact bool =false
if (seller.Quantity >=buyer.Quantity &&seller.PerShare == buyer.PerShare && seller.ShareName ==buyer.ShareName){
isallowTransact=true;
}
return isallowTransact
}
func executeTransaction(seller Seller,buyer Buyer) {
seller.Holdings -=seller.Quantity;
buyer.Holdings +=seller.Quantity;
fmt.Printf("seller current holding : %d, \n buyyer current holding: %d",seller.Holdings,buyer.Holdings)
}
func main() {
sellerJson :=`{"name":"pavan","ShareName":"TCS","holdings":100,"quantity":30,"perShare":11.11}`
buyerJson :=`{"name":"Raju","ShareName":"TCS","holdings":0,"quantity":30,"perShare":14.11}`
var seller Seller
var buyer Buyer
json.Unmarshal([]byte(sellerJson ), &seller)
json.Unmarshal([]byte(buyerJson ), &buyer)
//fmt.Printf("seller name : %s, shares of firm: %s,total holdings: %d, want to sell: %d,unit cost: %f", seller.Name , seller.ShareName,seller.Holdings , seller.Quantity,seller.PerShare )
var isallowExecute bool =false
isallowExecute =validateTransaction(seller,buyer)
if(isallowExecute){
executeTransaction(seller,buyer)
}else{
fmt.Print("\n seems buyer quotes are not matching with seller so we are not able to perform transacrion ,Please check and try again");
}
fmt.Println("\n Happy Trading...!!");
}
Update: This answer is wrong; I'm leaving it as an example of what not to do.
You should look it up with a regex then (pseudocode):
String s = {json source};
int i = s.indexOf("\"title\": \"")
s.substring(i,s.indexOf("\"",i))
more on substrings in Java

golang - fomatting struct to json

Does anyone know how to set the tag names for multilevel structs?
The top level tag-names of the struct works ok, but all sublevels tag names have the same name as in the struct. Trying to set all tag-name to lowercase.
The code can be run here:
package main
import (
"encoding/json"
"log"
)
type Source struct {
Pointer string `json:pointer,omitempty"`
Parameter string `json:parameter,omitempty"`
}
type Error struct {
Status int `json:"status,omitempty"`
Source *Source `json:"source,omitempty"`
Title string `json:"title,omitempty"`
Detail string `json:"detail,omitempty"`
}
type Errors struct {
Errors *[]Error `json:"errors"`
}
func main() {
errors := new(Errors)
errors.Errors = new([]Error)
error := new(Error)
error.Source = new(Source)
error.Source.Pointer = "pointer"
error.Status = 401
error.Title = "title"
error.Detail = "detail"
*errors.Errors = append(*(errors.Errors), *error)
response, _ := json.Marshal(errors)
log.Println("response", string(response))
}
Output:
{
"errors": [
{
"status": 400,
"source": {
"Pointer": "pointer",
"Parameter": ""
},
"title": "title",
"detail": "detail"
}
]
}
You've missed a few quotes:
Pointer string `json:pointer,omitempty"`
Parameter string `json:parameter,omitempty"`
// ^^^ Here.
Playground: https://play.golang.org/p/P3oHK29VKQ.