how made the Get result always ordered
jujiale opened this issue · 2 comments
hello:
I have a special business requirements,which demand the Get() method return result must have the same order always.
such as below:
`
func main() {
var s string = "{\"name\":\"tom\",\"age\":18, \"high\":1.68,\"language\":[\"java\",\"python\",\"go\"],\"partner\":{\"name\":\"jerry\",\"age\":20}}"
var jsonData interface{}
if err := sonic.Unmarshal([]byte(s), &jsonData); err != nil {
fmt.Println("Error unmarshaling JSON:", err)
return
}
expr, err := jp.ParseString("$.*")
if err != nil {
fmt.Println("Error parsing JSONPath expression:", err)
return
}
results := expr.Get(jsonData)
fmt.Println(results)
}
`
run the main several times, the result as below:
`
[18 1.68 [java python go] map[age:20 name:jerry] tom]
[1.68 [java python go] map[age:20 name:jerry] tom 18]
[[java python go] map[age:20 name:jerry] tom 18 1.68]
[18 1.68 [java python go] map[age:20 name:jerry] tom]
[1.68 [java python go] map[age:20 name:jerry] tom 18]
`
as you see, I run main method 5 times,the result is three different orders.
I want to konw, if have some strategy to achieve this, thank you.
the version we use is github.com/ohler55/ojg v1.23.0
In go and many other languages map/hash/object entries are not ordered. Since the order is not consistent from one run to the next in go maps the order of the output will not be ordered.
I answer to the second part about a strategy to achieve ordered output, take a look the way the writers in the oj, sen, or pretty packages. Basically the approach is to walk the data and for each map pull the keys, sort the keys, and then get the value for each key.
Depending on what you are looking for another approach would be to use the jp.Walk function to collect path/value pairs, sort those and that will give consistent results.
thanks for your reply