Unformated string to JSON

I would like to convert string like this

1:S 2:L 3:I 4:I 5:I 6:I 7:I 8:I 9:I 10:I 11:I 12:L 13:I 14:I 15:I 16:I

to JSON struct

type Item struct {
	Id  int
	Status string
}

My code looks like

package main

import (
	"fmt"
	"encoding/json"
)

type Item struct {
	Id  int
	Status string
}

var str = "1:I 2:I 3:I 4:I 5:I 6:I 7:I 8:I 9:I 10:I 11:I 12:L 13:I 14:I 15:I 16:I"

func main() {
	fmt.Println(str)
	    	
	var results []map[string]interface{}
	
	json.Unmarshal([]byte(str), &results)
	
	out, _ := json.Marshal(results)
	println(string(out))	
}

Whether such mapping is possible or I should add comma and quotation marks in the string ?
Any help will be welcome.

1 Like

Directly it is not possible because the string is not a valid jaon string.
But you can process that string and built a slice of Item. Something like :

func string2Item(str string) []Item {
   data := strings.Split(str, " ")
   len := len(data)
   result := make([]Item, len)

  for i:=0; i < len; i++ {
     value := data[i]
     tokens := strings.Split(value, ":")

     id, _ := strconv.Atoi(tokens[0])
     result[i] = Item{ Id : id, Status : tokens[1]}
   }    
   return result
}

And in your func main :

results := string2Item(str)
out, _ := json.Marshal(results)
println(string(out))
3 Likes

Thank you for your help. It’s working correctly.

1 Like

Great!!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.