go-zero
go-zero copied to clipboard
Why doesn’t parsing malformed JSON data support interface{}?
I defined a field as interface{} in the .api file, but httpx.Parse just won’t work with it, and throws an error:
type mismatch for field “evaluation”
The reason is that the incoming data structure is inconsistent. Since interface{} can be defined, why can’t it be received?
All I want to do is pass it in, convert it to a JSON string, and write it to the database. Later, I’ll retrieve it and handle it the same way. Given that it’s defined as interface{}, it should allow flexible usage, rather than being strictly tied to a fixed struct.
我在.api文件定义了某字段为interface{}, 但是在httpx.Parse的时候死活过不去, 提示:
type mismatch for field "evaluation"
因为这部分传过来的数据结构不统一, 既然interface{}能被定义, 为什么就不能接收, 我只想传入之后用进行json转换成字符串然后写入数据库, 然后同样取出, 既然定义为interface{} 应该就能灵活使用, 而不是定死为结构体.
Hello,
Thank you for raising this question about using interface{} in go-zero API files.
Go-zero intentionally doesn't support interface{} in API files by design. This is because one of the core principles of go-zero is to ensure well-defined schemas and consistent API contracts. Using interface{} would introduce ambiguity and make it harder to validate, document, and maintain the API contract.
For your use case where you need to handle data with inconsistent structures that will be converted to JSON strings for storage, we recommend defining the field as a string type in your API file instead. You can then:
- Receive the raw JSON as a string
- Store it directly in your database
- Retrieve it as a string when needed
- Parse it as needed in your application logic
This approach maintains the schema clarity that go-zero promotes while still giving you the flexibility to handle dynamic data structures.
If you need more specific guidance on implementing this approach in your application, please let us know.
Hope this helps!