steebchen / prisma-client-go

Prisma Client Go is an auto-generated and fully type-safe database client
https://goprisma.org
Apache License 2.0
2.13k stars 95 forks source link

JSON marshal Escape #1127

Open salmonsec opened 10 months ago

salmonsec commented 10 months ago

Is there a particular reason for using fmt %q to return the inner Raw Json struct for a JSON type field?

// MarshalJSON returns m as the JSON encoding of m.
func (m JSON) MarshalJSON() ([]byte, error) {
    if m == nil {
        return []byte("null"), nil
    }
    return []byte(fmt.Sprintf("%q", m)), nil
}

I've found that when I try to marshal a generated data type with a JSON field, I get results like this:

{"id":1,"customer_id":1,"data":[{"id":1,"context_bundle_id":1,"plugin_name":"test","method_name":"test","data":"{\"Objects\":{\"list/default/pod/app-9178234h-123n128\":{\"metadata\":{\"creationTimestamp\":null},\"template\":{\"metadata\":{\"creationTimestamp\":null},\"spec\":{\"containers\":[{\"name\":\"test\",\"image\":\"test\",\"resources\":{}}]}}}}}"}]}

Where data.data is of type JSON, it is escaping the quotes (treating it as a string) rather than printing the JSON object. This adds an extra step of processing at the end to have a generic JSON viewer display this correctly.

When MarshalJSON is replaced with a copy of the built-in functionality, it is written as expected.

func (m JSON) MarshalJSON() ([]byte, error) {
    if m == nil {
        return []byte("null"), nil
    }
    return m, nil
}

Result:

{"id":1,"customer_id":1,"data":[{"id":1,"context_bundle_id":1,"plugin_name":"test","method_name":"test","data":{"Objects":{"list/default/pod/app-9178234h-123n128":{"metadata":{"creationTimestamp":null},"template":{"metadata":{"creationTimestamp":null},"spec":{"containers":[{"name":"test","image":"test","resources":{}}]}}}}}}]}
steebchen commented 10 months ago

Thanks for the report. The reason %q is used internally is because the Prisma query engine stringifies JSON. However, this should obviously not happen in the marshal func for the end user. I'll look into it in the next few days.

hypecode-tech commented 1 month ago

Is this bug still open ? Because our team while they have been developing an api faced with this issue. Data have been written in postgesql and stored as json object when they fetch data from db it gives string json? marked field in schema.prisma. Could you inform me ?