Golang JSON Serialization/DeserializationSerializing to JSON in jQueryHow do I format a Microsoft JSON date?Can comments be used in JSON?How can I pretty-print JSON in a shell script?What is the correct JSON content type?.NET - JSON serialization of enum as stringWhy does Google prepend while(1); to their JSON responses?Deserialize JSON into C# dynamic object?Parse JSON in JavaScript?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?

How to deceive the MC

Flatten not working

Comparison of bool data types in C++

Did Game of Thrones end the way that George RR Martin intended?

Is it normal to "extract a paper" from a master thesis?

To exponential digit growth and beyond!

Paired t-test means that the variances of the 2 samples are the same?

Split into three!

Toxic, harassing lab environment

Why do the i8080 I/O instructions take a byte-sized operand to determine the port?

Why did OJ Simpson's trial take 9 months?

Physical only checkdb is failing, but full one is completed successfully

Why does the painters tape have to be blue?

Ribbon Cable Cross Talk - Is there a fix after the fact?

What is the purpose of the yellow wired panels on the IBM 360 Model 20?

Quantum corrections to geometry

What did the 'turbo' button actually do?

Why is 'additive' EQ more difficult to use than 'subtractive'?

If I arrive in the UK, and then head to mainland Europe, does my Schengen visa 90 day limit start when I arrived in the UK, or mainland Europe?

Why did other houses not demand this?

Goldfish unresponsive, what should I do?

Was this scene in S8E06 added because of fan reactions to S8E04?

How can I tell if a breaker uses both phases/legs

Is there an idiom that means that you are in a very strong negotiation position in a negotiation?



Golang JSON Serialization/Deserialization


Serializing to JSON in jQueryHow do I format a Microsoft JSON date?Can comments be used in JSON?How can I pretty-print JSON in a shell script?What is the correct JSON content type?.NET - JSON serialization of enum as stringWhy does Google prepend while(1); to their JSON responses?Deserialize JSON into C# dynamic object?Parse JSON in JavaScript?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-1















I have a struct as follows:



type Node struct 
Name string
Children []*Node
Values []string



I also have a set of json files describing my trees such as:




"something":
"someblah": [
"fluf",
"glah"
],
"someother":
"someotter": [
"blib",
"fnar"
]





How can I deserialize these files into the structs?



All the examples I found seem to require a different structure with named key/value pairs.



For this, the structure is key:



  • the key is the struct name

  • the map contents are children

  • the lists contents are values

I cannot understand how to map this logic into the golang json serializer.










share|improve this question






















  • why not unmarshal into map[string]interface?

    – Abdullah
    Mar 23 at 22:45

















-1















I have a struct as follows:



type Node struct 
Name string
Children []*Node
Values []string



I also have a set of json files describing my trees such as:




"something":
"someblah": [
"fluf",
"glah"
],
"someother":
"someotter": [
"blib",
"fnar"
]





How can I deserialize these files into the structs?



All the examples I found seem to require a different structure with named key/value pairs.



For this, the structure is key:



  • the key is the struct name

  • the map contents are children

  • the lists contents are values

I cannot understand how to map this logic into the golang json serializer.










share|improve this question






















  • why not unmarshal into map[string]interface?

    – Abdullah
    Mar 23 at 22:45













-1












-1








-1








I have a struct as follows:



type Node struct 
Name string
Children []*Node
Values []string



I also have a set of json files describing my trees such as:




"something":
"someblah": [
"fluf",
"glah"
],
"someother":
"someotter": [
"blib",
"fnar"
]





How can I deserialize these files into the structs?



All the examples I found seem to require a different structure with named key/value pairs.



For this, the structure is key:



  • the key is the struct name

  • the map contents are children

  • the lists contents are values

I cannot understand how to map this logic into the golang json serializer.










share|improve this question














I have a struct as follows:



type Node struct 
Name string
Children []*Node
Values []string



I also have a set of json files describing my trees such as:




"something":
"someblah": [
"fluf",
"glah"
],
"someother":
"someotter": [
"blib",
"fnar"
]





How can I deserialize these files into the structs?



All the examples I found seem to require a different structure with named key/value pairs.



For this, the structure is key:



  • the key is the struct name

  • the map contents are children

  • the lists contents are values

I cannot understand how to map this logic into the golang json serializer.







json go serialization






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 23 at 22:02









WilbertWilbert

3,83242670




3,83242670












  • why not unmarshal into map[string]interface?

    – Abdullah
    Mar 23 at 22:45

















  • why not unmarshal into map[string]interface?

    – Abdullah
    Mar 23 at 22:45
















why not unmarshal into map[string]interface?

– Abdullah
Mar 23 at 22:45





why not unmarshal into map[string]interface?

– Abdullah
Mar 23 at 22:45












1 Answer
1






active

oldest

votes


















2














The easiest approach is to decode to map[string]interface and convert that to the desired structure:



var m map[string]interface
err := json.Unmarshal(data, &m)
if err != nil
// handle error

node := convert(m, "")

...

func convert(name string, m map[string]interface) *Node
n := NodeName: name
for k, v := range m
switch v := v.(type)
case []interface:
nn := NodeName: k
for _, e := range v
s, ok := e.(string)
if !ok
panic(fmt.Sprintf("expected string, got %T", e))

nn.Values = append(nn.Values, s)

n.Children = append(n.Children, &nn)
case map[string]interface:
n.Children = append(n.Children, convert(k, v))
default:
panic("unexpected type")


return &n



The convert function panics when it encounters a value of an unexpected type. Depending on the requirements of your application, you may want to ignore these values or return an error.



Run it on the playground.






share|improve this answer

























  • Thanks, this helped me find the correct solution. However, there seems to be a bug in the example: In the values case, there is no node created and the values are attached to the parent. In the example, each node has either children or values.

    – Wilbert
    Mar 24 at 20:23











  • @Wilbert See updated answer. It would have been helpful if the question showed an example of the expected result.

    – Cerise Limón
    Mar 24 at 20:40











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55318807%2fgolang-json-serialization-deserialization%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














The easiest approach is to decode to map[string]interface and convert that to the desired structure:



var m map[string]interface
err := json.Unmarshal(data, &m)
if err != nil
// handle error

node := convert(m, "")

...

func convert(name string, m map[string]interface) *Node
n := NodeName: name
for k, v := range m
switch v := v.(type)
case []interface:
nn := NodeName: k
for _, e := range v
s, ok := e.(string)
if !ok
panic(fmt.Sprintf("expected string, got %T", e))

nn.Values = append(nn.Values, s)

n.Children = append(n.Children, &nn)
case map[string]interface:
n.Children = append(n.Children, convert(k, v))
default:
panic("unexpected type")


return &n



The convert function panics when it encounters a value of an unexpected type. Depending on the requirements of your application, you may want to ignore these values or return an error.



Run it on the playground.






share|improve this answer

























  • Thanks, this helped me find the correct solution. However, there seems to be a bug in the example: In the values case, there is no node created and the values are attached to the parent. In the example, each node has either children or values.

    – Wilbert
    Mar 24 at 20:23











  • @Wilbert See updated answer. It would have been helpful if the question showed an example of the expected result.

    – Cerise Limón
    Mar 24 at 20:40















2














The easiest approach is to decode to map[string]interface and convert that to the desired structure:



var m map[string]interface
err := json.Unmarshal(data, &m)
if err != nil
// handle error

node := convert(m, "")

...

func convert(name string, m map[string]interface) *Node
n := NodeName: name
for k, v := range m
switch v := v.(type)
case []interface:
nn := NodeName: k
for _, e := range v
s, ok := e.(string)
if !ok
panic(fmt.Sprintf("expected string, got %T", e))

nn.Values = append(nn.Values, s)

n.Children = append(n.Children, &nn)
case map[string]interface:
n.Children = append(n.Children, convert(k, v))
default:
panic("unexpected type")


return &n



The convert function panics when it encounters a value of an unexpected type. Depending on the requirements of your application, you may want to ignore these values or return an error.



Run it on the playground.






share|improve this answer

























  • Thanks, this helped me find the correct solution. However, there seems to be a bug in the example: In the values case, there is no node created and the values are attached to the parent. In the example, each node has either children or values.

    – Wilbert
    Mar 24 at 20:23











  • @Wilbert See updated answer. It would have been helpful if the question showed an example of the expected result.

    – Cerise Limón
    Mar 24 at 20:40













2












2








2







The easiest approach is to decode to map[string]interface and convert that to the desired structure:



var m map[string]interface
err := json.Unmarshal(data, &m)
if err != nil
// handle error

node := convert(m, "")

...

func convert(name string, m map[string]interface) *Node
n := NodeName: name
for k, v := range m
switch v := v.(type)
case []interface:
nn := NodeName: k
for _, e := range v
s, ok := e.(string)
if !ok
panic(fmt.Sprintf("expected string, got %T", e))

nn.Values = append(nn.Values, s)

n.Children = append(n.Children, &nn)
case map[string]interface:
n.Children = append(n.Children, convert(k, v))
default:
panic("unexpected type")


return &n



The convert function panics when it encounters a value of an unexpected type. Depending on the requirements of your application, you may want to ignore these values or return an error.



Run it on the playground.






share|improve this answer















The easiest approach is to decode to map[string]interface and convert that to the desired structure:



var m map[string]interface
err := json.Unmarshal(data, &m)
if err != nil
// handle error

node := convert(m, "")

...

func convert(name string, m map[string]interface) *Node
n := NodeName: name
for k, v := range m
switch v := v.(type)
case []interface:
nn := NodeName: k
for _, e := range v
s, ok := e.(string)
if !ok
panic(fmt.Sprintf("expected string, got %T", e))

nn.Values = append(nn.Values, s)

n.Children = append(n.Children, &nn)
case map[string]interface:
n.Children = append(n.Children, convert(k, v))
default:
panic("unexpected type")


return &n



The convert function panics when it encounters a value of an unexpected type. Depending on the requirements of your application, you may want to ignore these values or return an error.



Run it on the playground.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 24 at 20:38

























answered Mar 23 at 23:04









Cerise LimónCerise Limón

57k57497




57k57497












  • Thanks, this helped me find the correct solution. However, there seems to be a bug in the example: In the values case, there is no node created and the values are attached to the parent. In the example, each node has either children or values.

    – Wilbert
    Mar 24 at 20:23











  • @Wilbert See updated answer. It would have been helpful if the question showed an example of the expected result.

    – Cerise Limón
    Mar 24 at 20:40

















  • Thanks, this helped me find the correct solution. However, there seems to be a bug in the example: In the values case, there is no node created and the values are attached to the parent. In the example, each node has either children or values.

    – Wilbert
    Mar 24 at 20:23











  • @Wilbert See updated answer. It would have been helpful if the question showed an example of the expected result.

    – Cerise Limón
    Mar 24 at 20:40
















Thanks, this helped me find the correct solution. However, there seems to be a bug in the example: In the values case, there is no node created and the values are attached to the parent. In the example, each node has either children or values.

– Wilbert
Mar 24 at 20:23





Thanks, this helped me find the correct solution. However, there seems to be a bug in the example: In the values case, there is no node created and the values are attached to the parent. In the example, each node has either children or values.

– Wilbert
Mar 24 at 20:23













@Wilbert See updated answer. It would have been helpful if the question showed an example of the expected result.

– Cerise Limón
Mar 24 at 20:40





@Wilbert See updated answer. It would have been helpful if the question showed an example of the expected result.

– Cerise Limón
Mar 24 at 20:40



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55318807%2fgolang-json-serialization-deserialization%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript