JSON Parsing in Go - Trick [duplicate]

Multi tool use
Multi tool use











up vote
-3
down vote

favorite













This question already has an answer here:




  • How to iterate through a map in golang in order?

    2 answers




How to parse this json using Go?



 timelinedata := '{
"2016-08-17T00:00:00.000Z": 4,
"2016-11-02T00:00:00.000Z": 1,
"2017-08-30T00:00:00.000Z": 1
} '


I want the dates and the values in separate variables by looping over the json.
Currently I am doing it in this way



var timeline map[string]int


json.Unmarshal(byte(timelinedata),



for k, v := range timeline {
new_key := k
new_val := v
println("val--->>", new_key, new_val)
}


The problem is that the output is not in proper order as like the json input is. Every time I run the loop the output order varies. I want to map the json in exact order as like the input. I think I am not maping it in a proper way---










share|improve this question













marked as duplicate by Flimzy, Bart Kiers parsing
Users with the  parsing badge can single-handedly close parsing questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 7 at 8:05


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.











  • 1




    Maps are unordered in go, that's why.
    – Ullaakut
    Nov 7 at 6:29






  • 3




    Well, you cannot do this (at least not in a simple way): Your JSON is an object and its fields are unordered. So are maps in Go. What you can do (See linked answer) is sort the timestamps. This will give you the time in sorted order which may differ from your input order (which is unordered). If your input really would have an order it would be ab JSON array and not an object.
    – Volker
    Nov 7 at 6:50










  • @Volker That actually qualifies to be the answer.
    – icza
    Nov 7 at 7:32















up vote
-3
down vote

favorite













This question already has an answer here:




  • How to iterate through a map in golang in order?

    2 answers




How to parse this json using Go?



 timelinedata := '{
"2016-08-17T00:00:00.000Z": 4,
"2016-11-02T00:00:00.000Z": 1,
"2017-08-30T00:00:00.000Z": 1
} '


I want the dates and the values in separate variables by looping over the json.
Currently I am doing it in this way



var timeline map[string]int


json.Unmarshal(byte(timelinedata),



for k, v := range timeline {
new_key := k
new_val := v
println("val--->>", new_key, new_val)
}


The problem is that the output is not in proper order as like the json input is. Every time I run the loop the output order varies. I want to map the json in exact order as like the input. I think I am not maping it in a proper way---










share|improve this question













marked as duplicate by Flimzy, Bart Kiers parsing
Users with the  parsing badge can single-handedly close parsing questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 7 at 8:05


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.











  • 1




    Maps are unordered in go, that's why.
    – Ullaakut
    Nov 7 at 6:29






  • 3




    Well, you cannot do this (at least not in a simple way): Your JSON is an object and its fields are unordered. So are maps in Go. What you can do (See linked answer) is sort the timestamps. This will give you the time in sorted order which may differ from your input order (which is unordered). If your input really would have an order it would be ab JSON array and not an object.
    – Volker
    Nov 7 at 6:50










  • @Volker That actually qualifies to be the answer.
    – icza
    Nov 7 at 7:32













up vote
-3
down vote

favorite









up vote
-3
down vote

favorite












This question already has an answer here:




  • How to iterate through a map in golang in order?

    2 answers




How to parse this json using Go?



 timelinedata := '{
"2016-08-17T00:00:00.000Z": 4,
"2016-11-02T00:00:00.000Z": 1,
"2017-08-30T00:00:00.000Z": 1
} '


I want the dates and the values in separate variables by looping over the json.
Currently I am doing it in this way



var timeline map[string]int


json.Unmarshal(byte(timelinedata),



for k, v := range timeline {
new_key := k
new_val := v
println("val--->>", new_key, new_val)
}


The problem is that the output is not in proper order as like the json input is. Every time I run the loop the output order varies. I want to map the json in exact order as like the input. I think I am not maping it in a proper way---










share|improve this question














This question already has an answer here:




  • How to iterate through a map in golang in order?

    2 answers




How to parse this json using Go?



 timelinedata := '{
"2016-08-17T00:00:00.000Z": 4,
"2016-11-02T00:00:00.000Z": 1,
"2017-08-30T00:00:00.000Z": 1
} '


I want the dates and the values in separate variables by looping over the json.
Currently I am doing it in this way



var timeline map[string]int


json.Unmarshal(byte(timelinedata),



for k, v := range timeline {
new_key := k
new_val := v
println("val--->>", new_key, new_val)
}


The problem is that the output is not in proper order as like the json input is. Every time I run the loop the output order varies. I want to map the json in exact order as like the input. I think I am not maping it in a proper way---





This question already has an answer here:




  • How to iterate through a map in golang in order?

    2 answers








json parsing go






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 7 at 6:21









zaheer abbas

234




234




marked as duplicate by Flimzy, Bart Kiers parsing
Users with the  parsing badge can single-handedly close parsing questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 7 at 8:05


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by Flimzy, Bart Kiers parsing
Users with the  parsing badge can single-handedly close parsing questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 7 at 8:05


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 1




    Maps are unordered in go, that's why.
    – Ullaakut
    Nov 7 at 6:29






  • 3




    Well, you cannot do this (at least not in a simple way): Your JSON is an object and its fields are unordered. So are maps in Go. What you can do (See linked answer) is sort the timestamps. This will give you the time in sorted order which may differ from your input order (which is unordered). If your input really would have an order it would be ab JSON array and not an object.
    – Volker
    Nov 7 at 6:50










  • @Volker That actually qualifies to be the answer.
    – icza
    Nov 7 at 7:32














  • 1




    Maps are unordered in go, that's why.
    – Ullaakut
    Nov 7 at 6:29






  • 3




    Well, you cannot do this (at least not in a simple way): Your JSON is an object and its fields are unordered. So are maps in Go. What you can do (See linked answer) is sort the timestamps. This will give you the time in sorted order which may differ from your input order (which is unordered). If your input really would have an order it would be ab JSON array and not an object.
    – Volker
    Nov 7 at 6:50










  • @Volker That actually qualifies to be the answer.
    – icza
    Nov 7 at 7:32








1




1




Maps are unordered in go, that's why.
– Ullaakut
Nov 7 at 6:29




Maps are unordered in go, that's why.
– Ullaakut
Nov 7 at 6:29




3




3




Well, you cannot do this (at least not in a simple way): Your JSON is an object and its fields are unordered. So are maps in Go. What you can do (See linked answer) is sort the timestamps. This will give you the time in sorted order which may differ from your input order (which is unordered). If your input really would have an order it would be ab JSON array and not an object.
– Volker
Nov 7 at 6:50




Well, you cannot do this (at least not in a simple way): Your JSON is an object and its fields are unordered. So are maps in Go. What you can do (See linked answer) is sort the timestamps. This will give you the time in sorted order which may differ from your input order (which is unordered). If your input really would have an order it would be ab JSON array and not an object.
– Volker
Nov 7 at 6:50












@Volker That actually qualifies to be the answer.
– icza
Nov 7 at 7:32




@Volker That actually qualifies to be the answer.
– icza
Nov 7 at 7:32












1 Answer
1






active

oldest

votes

















up vote
3
down vote



accepted










You should not assume that the key order in a JSON object means anything:



From the introduction of RFC 7159 (emphasis mine):




An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.



An array is an ordered sequence of zero or more values.




In addition to that, you shouldn't assume that the producer of the JSON document has been in control of the key/value order; maps are unordered in most languages, so it mostly comes down to the used encoding library. If the producer did care about the order, they would use an array.



That being said, if you really are interested in the order of the JSON keys, you have to decode the object piece by piece, using json.Decoder.Token:



package main

import (
"encoding/json"
"fmt"
"log"
"strings"
)

func main() {
j := `{
"2016-08-17T00:00:00.000Z": 4,
"2016-11-02T00:00:00.000Z": 1,
"2017-08-30T00:00:00.000Z": 1
}`

dec := json.NewDecoder(strings.NewReader(j))
for dec.More() {
t, err := dec.Token()
if err != nil {
log.Fatal(err)
}

switch t := t.(type) {
case json.Delim:
// no-op
case string:
fmt.Printf("%s => ", t)
case float64:
fmt.Printf("%.0fn", t)
case json.Number:
fmt.Printf(" %sn", t)
default:
log.Fatalf("Unexpected type: %T", t)
}
}
}


Try it on the Playground: https://play.golang.org/p/qfXcOfOvKws






share|improve this answer






























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    3
    down vote



    accepted










    You should not assume that the key order in a JSON object means anything:



    From the introduction of RFC 7159 (emphasis mine):




    An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.



    An array is an ordered sequence of zero or more values.




    In addition to that, you shouldn't assume that the producer of the JSON document has been in control of the key/value order; maps are unordered in most languages, so it mostly comes down to the used encoding library. If the producer did care about the order, they would use an array.



    That being said, if you really are interested in the order of the JSON keys, you have to decode the object piece by piece, using json.Decoder.Token:



    package main

    import (
    "encoding/json"
    "fmt"
    "log"
    "strings"
    )

    func main() {
    j := `{
    "2016-08-17T00:00:00.000Z": 4,
    "2016-11-02T00:00:00.000Z": 1,
    "2017-08-30T00:00:00.000Z": 1
    }`

    dec := json.NewDecoder(strings.NewReader(j))
    for dec.More() {
    t, err := dec.Token()
    if err != nil {
    log.Fatal(err)
    }

    switch t := t.(type) {
    case json.Delim:
    // no-op
    case string:
    fmt.Printf("%s => ", t)
    case float64:
    fmt.Printf("%.0fn", t)
    case json.Number:
    fmt.Printf(" %sn", t)
    default:
    log.Fatalf("Unexpected type: %T", t)
    }
    }
    }


    Try it on the Playground: https://play.golang.org/p/qfXcOfOvKws






    share|improve this answer



























      up vote
      3
      down vote



      accepted










      You should not assume that the key order in a JSON object means anything:



      From the introduction of RFC 7159 (emphasis mine):




      An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.



      An array is an ordered sequence of zero or more values.




      In addition to that, you shouldn't assume that the producer of the JSON document has been in control of the key/value order; maps are unordered in most languages, so it mostly comes down to the used encoding library. If the producer did care about the order, they would use an array.



      That being said, if you really are interested in the order of the JSON keys, you have to decode the object piece by piece, using json.Decoder.Token:



      package main

      import (
      "encoding/json"
      "fmt"
      "log"
      "strings"
      )

      func main() {
      j := `{
      "2016-08-17T00:00:00.000Z": 4,
      "2016-11-02T00:00:00.000Z": 1,
      "2017-08-30T00:00:00.000Z": 1
      }`

      dec := json.NewDecoder(strings.NewReader(j))
      for dec.More() {
      t, err := dec.Token()
      if err != nil {
      log.Fatal(err)
      }

      switch t := t.(type) {
      case json.Delim:
      // no-op
      case string:
      fmt.Printf("%s => ", t)
      case float64:
      fmt.Printf("%.0fn", t)
      case json.Number:
      fmt.Printf(" %sn", t)
      default:
      log.Fatalf("Unexpected type: %T", t)
      }
      }
      }


      Try it on the Playground: https://play.golang.org/p/qfXcOfOvKws






      share|improve this answer

























        up vote
        3
        down vote



        accepted







        up vote
        3
        down vote



        accepted






        You should not assume that the key order in a JSON object means anything:



        From the introduction of RFC 7159 (emphasis mine):




        An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.



        An array is an ordered sequence of zero or more values.




        In addition to that, you shouldn't assume that the producer of the JSON document has been in control of the key/value order; maps are unordered in most languages, so it mostly comes down to the used encoding library. If the producer did care about the order, they would use an array.



        That being said, if you really are interested in the order of the JSON keys, you have to decode the object piece by piece, using json.Decoder.Token:



        package main

        import (
        "encoding/json"
        "fmt"
        "log"
        "strings"
        )

        func main() {
        j := `{
        "2016-08-17T00:00:00.000Z": 4,
        "2016-11-02T00:00:00.000Z": 1,
        "2017-08-30T00:00:00.000Z": 1
        }`

        dec := json.NewDecoder(strings.NewReader(j))
        for dec.More() {
        t, err := dec.Token()
        if err != nil {
        log.Fatal(err)
        }

        switch t := t.(type) {
        case json.Delim:
        // no-op
        case string:
        fmt.Printf("%s => ", t)
        case float64:
        fmt.Printf("%.0fn", t)
        case json.Number:
        fmt.Printf(" %sn", t)
        default:
        log.Fatalf("Unexpected type: %T", t)
        }
        }
        }


        Try it on the Playground: https://play.golang.org/p/qfXcOfOvKws






        share|improve this answer














        You should not assume that the key order in a JSON object means anything:



        From the introduction of RFC 7159 (emphasis mine):




        An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.



        An array is an ordered sequence of zero or more values.




        In addition to that, you shouldn't assume that the producer of the JSON document has been in control of the key/value order; maps are unordered in most languages, so it mostly comes down to the used encoding library. If the producer did care about the order, they would use an array.



        That being said, if you really are interested in the order of the JSON keys, you have to decode the object piece by piece, using json.Decoder.Token:



        package main

        import (
        "encoding/json"
        "fmt"
        "log"
        "strings"
        )

        func main() {
        j := `{
        "2016-08-17T00:00:00.000Z": 4,
        "2016-11-02T00:00:00.000Z": 1,
        "2017-08-30T00:00:00.000Z": 1
        }`

        dec := json.NewDecoder(strings.NewReader(j))
        for dec.More() {
        t, err := dec.Token()
        if err != nil {
        log.Fatal(err)
        }

        switch t := t.(type) {
        case json.Delim:
        // no-op
        case string:
        fmt.Printf("%s => ", t)
        case float64:
        fmt.Printf("%.0fn", t)
        case json.Number:
        fmt.Printf(" %sn", t)
        default:
        log.Fatalf("Unexpected type: %T", t)
        }
        }
        }


        Try it on the Playground: https://play.golang.org/p/qfXcOfOvKws







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 7 at 8:48

























        answered Nov 7 at 7:41









        Peter

        14.8k42032




        14.8k42032















            neuZeZaz
            m,V eZ8z,83,9km XLBWi1IDkf

            Popular posts from this blog

            横浜市

            Rostock

            Europa