Create Json keys dynamically

Hi!,

I’m Go beginner and new to this forum community.

I have text files that have the same structure text = value per line and I would like to transform each file to a json file.

Example:

file 1:

    city =  Berlin,  inhabitant = 10 
    city =  London,  inhabitant = 20 

file 2:

    color =  blue,  size = 10
    color =  red,  size = 20

file 3 (contains dupplicate entries that I want to keep):

    color =  blue,  size = 10, size = 10
    color =  red,  size = 20, size = 20

Json expected:

file1: [
        {
           "city" :  "Berlin",  "inhabitant" : 10 
        }, 
        {
           "city" :  "London",  "inhabitant" : 20 
        }
]

file2: [
     {
        "color" :  "blue", 
        "size" : 10 
     }, 
     {
        "color" :  "red",  
        "size" :  20 
     }
]

file3: [
      {
          "color" : "blue",  
          "size" : 10, 
          "size" : 10 
       }, 
       {
           "color" : "red",  
            "size" : 20, 
            "size" : 20 
       }
]

How can I transform a key (city,color,size) dynamically for each files?
Can the usage of interface{} the way to do it ?

Thank you!

Pascal

is not valid json. Same attribute can’t occur more than once. You could make maybe it into a array instead

{ "color" : "red", "size" : [20, 20] }
1 Like

Thank you for you answer.

I have decided to don’t care about duplicate anymore.
I use a map[int]map[string]string that I convert to json and with json.MarshalIndent() I come on the result I was expected for.

2 Likes

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