get http.Response into struct using json.UnmarshalWhy can't I assign a *Struct to an *Interface?json.Unmarshal doesn't seem to pay attention to struct tagsDecoding JSON in Golang using json.Unmarshal vs json.NewDecoder.DecodeHow to print struct variables in console?Reading http.Response Body streamGo json.Unmarshal returns false structCan't Json.Unmarshal to a structAssign additional field when unmarshalling JSON object to GO structUse a seed for json.Unmarshal into a slice structhow to parse golang json array having random hash value in field name

Dirichlet series with a single zero

Meaning of the (idiomatic?) expression "seghe mentali"

Endgame puzzle: How to avoid stalemate and win?

Madam I m Adam..please don’t get mad..you will no longer be prime

about academic proof-reading, what to do in this situation?

Where are the "shires" in the UK?

How to display number in triangular pattern with plus sign

Simple Derivative Proof?

no sense/need/point

Table coloring doesn't extend all the way with makecell

Would a "Permanence" spell in 5e be overpowered?

Is it normal for gliders not to have attitude indicators?

Where did Lovecraft write about Carcosa?

How to pass hash as password to ssh server

What is a precise issue with allowing getters?

How can I decipher which graph belongs to which equation?

Has the United States ever had a non-Christian President?

Can the Tidal Wave spell trigger a vampire's weakness to running water?

Looking for sci-fi book based on Hinduism/Buddhism

Krull dimension of the ring of global sections

Is the book wrong about the Nyquist Sampling Criterion?

Why are oscilloscope input impedances so low?

Constitutional limitation of criminalizing behavior in US law?

If an old FIN is delivered, will TCP terminate the new connection?



get http.Response into struct using json.Unmarshal


Why can't I assign a *Struct to an *Interface?json.Unmarshal doesn't seem to pay attention to struct tagsDecoding JSON in Golang using json.Unmarshal vs json.NewDecoder.DecodeHow to print struct variables in console?Reading http.Response Body streamGo json.Unmarshal returns false structCan't Json.Unmarshal to a structAssign additional field when unmarshalling JSON object to GO structUse a seed for json.Unmarshal into a slice structhow to parse golang json array having random hash value in field name






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








0















I'm calling a remote API and getting a JSON response back. I'm trying to convert the *http.Response into a struct that I defined. Everything i've tried so far has resulted in an empty struct. Here is my attempt with json.Unmarshal



type Summary struct 
Created string `json:"created"`
High float64 `json:"high"`
Low float64 `json:"low"`


func getSummary()

url := "http://myurl"

resp, err := http.Get(url)
if err != nil
log.Fatalln(err)


body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil
panic(err.Error())


log.Printf("body = %v", string(body))
//outputs: "success":true,"message":"","result":["High":0.43600000,"Low":0.43003737],"Created":"2017-06-25T03:06:46.83"]

var summary = new(Summary)
err3 := json.Unmarshal(body, &summary)
if err3 != nil
fmt.Println("whoops:", err3)
//outputs: whoops: <nil>


log.Printf("s = %v", summary)
//outputs: s = &0 0 0 0 0 0 0 0 0 0


}


What am I doing wrong? The JSON tags in my struct match the json keys from the response exactly...



edit: here is the JSON returned from the API




"success": true,
"message": "''",
"result": [

"High": 0.0135,
"Low": 0.012,
"Created": "2014-02-13T00:00:00"

]



edit
i changed the struct to this but still not working



type Summary struct 
Result struct
Created string `json:"created"`
High float64 `json:"high"`
Low float64 `json:"low"`











share|improve this question
























  • yea the program prints the whoops error. Using %v outputs the exact same

    – MikeG
    Mar 23 at 4:13












  • I added an update. Why is the output of err3 = <nil> if the previous if statement requires that eer3 is not nil?

    – MikeG
    Mar 23 at 4:22











  • body is not valid JSON. You have to remove the %!(EXTRA string= and the ) in order to be able to use json.Unmarshal on it.

    – Joel Cornett
    Mar 23 at 4:31











  • Additionally Summary is not the same shape as the JSON data anyway. You need to make it match the shape of the whole JSON object (after removing the portions mentioned above) in order to be able to unmarshal it.

    – Joel Cornett
    Mar 23 at 4:33






  • 1





    please add the response JSON in the question.

    – Sathishkumar Rakkiasamy
    Mar 23 at 4:58

















0















I'm calling a remote API and getting a JSON response back. I'm trying to convert the *http.Response into a struct that I defined. Everything i've tried so far has resulted in an empty struct. Here is my attempt with json.Unmarshal



type Summary struct 
Created string `json:"created"`
High float64 `json:"high"`
Low float64 `json:"low"`


func getSummary()

url := "http://myurl"

resp, err := http.Get(url)
if err != nil
log.Fatalln(err)


body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil
panic(err.Error())


log.Printf("body = %v", string(body))
//outputs: "success":true,"message":"","result":["High":0.43600000,"Low":0.43003737],"Created":"2017-06-25T03:06:46.83"]

var summary = new(Summary)
err3 := json.Unmarshal(body, &summary)
if err3 != nil
fmt.Println("whoops:", err3)
//outputs: whoops: <nil>


log.Printf("s = %v", summary)
//outputs: s = &0 0 0 0 0 0 0 0 0 0


}


What am I doing wrong? The JSON tags in my struct match the json keys from the response exactly...



edit: here is the JSON returned from the API




"success": true,
"message": "''",
"result": [

"High": 0.0135,
"Low": 0.012,
"Created": "2014-02-13T00:00:00"

]



edit
i changed the struct to this but still not working



type Summary struct 
Result struct
Created string `json:"created"`
High float64 `json:"high"`
Low float64 `json:"low"`











share|improve this question
























  • yea the program prints the whoops error. Using %v outputs the exact same

    – MikeG
    Mar 23 at 4:13












  • I added an update. Why is the output of err3 = <nil> if the previous if statement requires that eer3 is not nil?

    – MikeG
    Mar 23 at 4:22











  • body is not valid JSON. You have to remove the %!(EXTRA string= and the ) in order to be able to use json.Unmarshal on it.

    – Joel Cornett
    Mar 23 at 4:31











  • Additionally Summary is not the same shape as the JSON data anyway. You need to make it match the shape of the whole JSON object (after removing the portions mentioned above) in order to be able to unmarshal it.

    – Joel Cornett
    Mar 23 at 4:33






  • 1





    please add the response JSON in the question.

    – Sathishkumar Rakkiasamy
    Mar 23 at 4:58













0












0








0








I'm calling a remote API and getting a JSON response back. I'm trying to convert the *http.Response into a struct that I defined. Everything i've tried so far has resulted in an empty struct. Here is my attempt with json.Unmarshal



type Summary struct 
Created string `json:"created"`
High float64 `json:"high"`
Low float64 `json:"low"`


func getSummary()

url := "http://myurl"

resp, err := http.Get(url)
if err != nil
log.Fatalln(err)


body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil
panic(err.Error())


log.Printf("body = %v", string(body))
//outputs: "success":true,"message":"","result":["High":0.43600000,"Low":0.43003737],"Created":"2017-06-25T03:06:46.83"]

var summary = new(Summary)
err3 := json.Unmarshal(body, &summary)
if err3 != nil
fmt.Println("whoops:", err3)
//outputs: whoops: <nil>


log.Printf("s = %v", summary)
//outputs: s = &0 0 0 0 0 0 0 0 0 0


}


What am I doing wrong? The JSON tags in my struct match the json keys from the response exactly...



edit: here is the JSON returned from the API




"success": true,
"message": "''",
"result": [

"High": 0.0135,
"Low": 0.012,
"Created": "2014-02-13T00:00:00"

]



edit
i changed the struct to this but still not working



type Summary struct 
Result struct
Created string `json:"created"`
High float64 `json:"high"`
Low float64 `json:"low"`











share|improve this question
















I'm calling a remote API and getting a JSON response back. I'm trying to convert the *http.Response into a struct that I defined. Everything i've tried so far has resulted in an empty struct. Here is my attempt with json.Unmarshal



type Summary struct 
Created string `json:"created"`
High float64 `json:"high"`
Low float64 `json:"low"`


func getSummary()

url := "http://myurl"

resp, err := http.Get(url)
if err != nil
log.Fatalln(err)


body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil
panic(err.Error())


log.Printf("body = %v", string(body))
//outputs: "success":true,"message":"","result":["High":0.43600000,"Low":0.43003737],"Created":"2017-06-25T03:06:46.83"]

var summary = new(Summary)
err3 := json.Unmarshal(body, &summary)
if err3 != nil
fmt.Println("whoops:", err3)
//outputs: whoops: <nil>


log.Printf("s = %v", summary)
//outputs: s = &0 0 0 0 0 0 0 0 0 0


}


What am I doing wrong? The JSON tags in my struct match the json keys from the response exactly...



edit: here is the JSON returned from the API




"success": true,
"message": "''",
"result": [

"High": 0.0135,
"Low": 0.012,
"Created": "2014-02-13T00:00:00"

]



edit
i changed the struct to this but still not working



type Summary struct 
Result struct
Created string `json:"created"`
High float64 `json:"high"`
Low float64 `json:"low"`








go






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 5:01







MikeG

















asked Mar 23 at 3:28









MikeGMikeG

2,02911436




2,02911436












  • yea the program prints the whoops error. Using %v outputs the exact same

    – MikeG
    Mar 23 at 4:13












  • I added an update. Why is the output of err3 = <nil> if the previous if statement requires that eer3 is not nil?

    – MikeG
    Mar 23 at 4:22











  • body is not valid JSON. You have to remove the %!(EXTRA string= and the ) in order to be able to use json.Unmarshal on it.

    – Joel Cornett
    Mar 23 at 4:31











  • Additionally Summary is not the same shape as the JSON data anyway. You need to make it match the shape of the whole JSON object (after removing the portions mentioned above) in order to be able to unmarshal it.

    – Joel Cornett
    Mar 23 at 4:33






  • 1





    please add the response JSON in the question.

    – Sathishkumar Rakkiasamy
    Mar 23 at 4:58

















  • yea the program prints the whoops error. Using %v outputs the exact same

    – MikeG
    Mar 23 at 4:13












  • I added an update. Why is the output of err3 = <nil> if the previous if statement requires that eer3 is not nil?

    – MikeG
    Mar 23 at 4:22











  • body is not valid JSON. You have to remove the %!(EXTRA string= and the ) in order to be able to use json.Unmarshal on it.

    – Joel Cornett
    Mar 23 at 4:31











  • Additionally Summary is not the same shape as the JSON data anyway. You need to make it match the shape of the whole JSON object (after removing the portions mentioned above) in order to be able to unmarshal it.

    – Joel Cornett
    Mar 23 at 4:33






  • 1





    please add the response JSON in the question.

    – Sathishkumar Rakkiasamy
    Mar 23 at 4:58
















yea the program prints the whoops error. Using %v outputs the exact same

– MikeG
Mar 23 at 4:13






yea the program prints the whoops error. Using %v outputs the exact same

– MikeG
Mar 23 at 4:13














I added an update. Why is the output of err3 = <nil> if the previous if statement requires that eer3 is not nil?

– MikeG
Mar 23 at 4:22





I added an update. Why is the output of err3 = <nil> if the previous if statement requires that eer3 is not nil?

– MikeG
Mar 23 at 4:22













body is not valid JSON. You have to remove the %!(EXTRA string= and the ) in order to be able to use json.Unmarshal on it.

– Joel Cornett
Mar 23 at 4:31





body is not valid JSON. You have to remove the %!(EXTRA string= and the ) in order to be able to use json.Unmarshal on it.

– Joel Cornett
Mar 23 at 4:31













Additionally Summary is not the same shape as the JSON data anyway. You need to make it match the shape of the whole JSON object (after removing the portions mentioned above) in order to be able to unmarshal it.

– Joel Cornett
Mar 23 at 4:33





Additionally Summary is not the same shape as the JSON data anyway. You need to make it match the shape of the whole JSON object (after removing the portions mentioned above) in order to be able to unmarshal it.

– Joel Cornett
Mar 23 at 4:33




1




1





please add the response JSON in the question.

– Sathishkumar Rakkiasamy
Mar 23 at 4:58





please add the response JSON in the question.

– Sathishkumar Rakkiasamy
Mar 23 at 4:58












2 Answers
2






active

oldest

votes


















2














Change your structure like this



type Summary struct 
Sucess bool `json:"success"`
Message string `json:"message"`
Result []Result `json:"result"`


type Result struct
Created string `json:"Created"`
High float64 `json:"High"`
Low float64 `json:"Low"`



Try this link






share|improve this answer
































    0














    Its because you're trying to unmarshal an array into struct,
    Use array instead of the Result struct



    type Summary struct 
    Result []struct
    Created string `json:"created"`
    High float64 `json:"high"`
    Low float64 `json:"low"`




    Use this weblink to convert your JSON objects to Go Struct >> https://mholt.github.io/json-to-go/






    share|improve this answer























      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%2f55310349%2fget-http-response-into-struct-using-json-unmarshal%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      Change your structure like this



      type Summary struct 
      Sucess bool `json:"success"`
      Message string `json:"message"`
      Result []Result `json:"result"`


      type Result struct
      Created string `json:"Created"`
      High float64 `json:"High"`
      Low float64 `json:"Low"`



      Try this link






      share|improve this answer





























        2














        Change your structure like this



        type Summary struct 
        Sucess bool `json:"success"`
        Message string `json:"message"`
        Result []Result `json:"result"`


        type Result struct
        Created string `json:"Created"`
        High float64 `json:"High"`
        Low float64 `json:"Low"`



        Try this link






        share|improve this answer



























          2












          2








          2







          Change your structure like this



          type Summary struct 
          Sucess bool `json:"success"`
          Message string `json:"message"`
          Result []Result `json:"result"`


          type Result struct
          Created string `json:"Created"`
          High float64 `json:"High"`
          Low float64 `json:"Low"`



          Try this link






          share|improve this answer















          Change your structure like this



          type Summary struct 
          Sucess bool `json:"success"`
          Message string `json:"message"`
          Result []Result `json:"result"`


          type Result struct
          Created string `json:"Created"`
          High float64 `json:"High"`
          Low float64 `json:"Low"`



          Try this link







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 23 at 7:01

























          answered Mar 23 at 5:38









          Maruthi AdithyaMaruthi Adithya

          1,11311022




          1,11311022























              0














              Its because you're trying to unmarshal an array into struct,
              Use array instead of the Result struct



              type Summary struct 
              Result []struct
              Created string `json:"created"`
              High float64 `json:"high"`
              Low float64 `json:"low"`




              Use this weblink to convert your JSON objects to Go Struct >> https://mholt.github.io/json-to-go/






              share|improve this answer



























                0














                Its because you're trying to unmarshal an array into struct,
                Use array instead of the Result struct



                type Summary struct 
                Result []struct
                Created string `json:"created"`
                High float64 `json:"high"`
                Low float64 `json:"low"`




                Use this weblink to convert your JSON objects to Go Struct >> https://mholt.github.io/json-to-go/






                share|improve this answer

























                  0












                  0








                  0







                  Its because you're trying to unmarshal an array into struct,
                  Use array instead of the Result struct



                  type Summary struct 
                  Result []struct
                  Created string `json:"created"`
                  High float64 `json:"high"`
                  Low float64 `json:"low"`




                  Use this weblink to convert your JSON objects to Go Struct >> https://mholt.github.io/json-to-go/






                  share|improve this answer













                  Its because you're trying to unmarshal an array into struct,
                  Use array instead of the Result struct



                  type Summary struct 
                  Result []struct
                  Created string `json:"created"`
                  High float64 `json:"high"`
                  Low float64 `json:"low"`




                  Use this weblink to convert your JSON objects to Go Struct >> https://mholt.github.io/json-to-go/







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 23 at 5:45









                  Aruna PrabashwaraAruna Prabashwara

                  12




                  12



























                      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%2f55310349%2fget-http-response-into-struct-using-json-unmarshal%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

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현