mholt / json-to-go

Translates JSON into a Go type in your browser instantly (original)
https://mholt.github.io/json-to-go/
MIT License
4.48k stars 473 forks source link

Fix greedy regex causing time.Time #123

Closed ejcx closed 10 months ago

ejcx commented 10 months ago

The code in question is this small two lines.

if (/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)/.test(val))
  return "time.Time";

But what happens if the string in the object contains a timestamp and a bunch of other junk meaning it isn't a time at all, but rather just a string. There's a lot of valid use cases for this. For example, parsing syslog...or something.

let val = "2023-11-03T02:18:10+00:00 my name is bob"
if (/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)/.test(val)) {
    console.log("time.Time");
}
> time.Time

Oh no. It also seems to function in this way when the extra junk is on the other side of the timestamp.

let val = "my name is bob 2023-11-03T02:18:10+00:00"
if (/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)/.test(val)) {
    console.log("time.Time");
}
> time.Time

That's no fun. This is easy to overlook, and luckily it's a simple fix.

let val = "2023-11-03T02:18:10+00:00 my name is bob"
if (/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)$/.test(val)) {
    console.log("time.Time");
} else {
    console.log("Fixed")
}
> Fixed

Reference #122