php editor Xiaoxin will introduce you to a method of dynamically changing JSON key values during the Marshal and Unmarshal processes. When processing JSON data, sometimes we need to modify or replace key values. This article will share a simple yet effective technique to help developers achieve this goal in PHP. By using some specific functions and technologies, we can easily operate on JSON data and achieve the need to dynamically change key values. Next, please follow the editor to learn this practical technique!
I am forced to use an API that has two different keys or identifiers for the same object (VAT number). Depends on whether the call is GET or POST/PATCH
In the GET I have to unmarshal/decode the json using this structure:
type SilverfinCompany struct { ID int `json:"id"` Name string `json:"name"` Vat string `json:"vat"` // here }
In POST and PATCH I can use this structure to marshal the data into json:
<code>type SilverfinCompany struct { ID int `json:"id"` Name string `json:"name"` Vat string `json:"vat_identifier"` // here } </code>
The obvious solution is to have two "different" structures with the same content but slightly different JSON keys, and two conversion functions. Or have two different fields in the structure: Vat and VatIndentifier.
The problem is that it adds extra complexity to already complex code.
So I want to know:
Is there a way (similar to reflection) to change the JSON key of the Vat field in the structure depending on the situation?
You cannot modify type definitions, including structure tags, at runtime.
As long as the field types and order (i.e. memory layout) are the same, there is no need for any conversion functions at all, they can be converted directly: https://go.dev/play/p/IhkVM-BMLiY
func main() { foo := SilverfinCompanyFoo{ ID: 1, Name: "Baz", Vat: "Qux", } bar := SilverfinCompanyBar(foo) fmt.Println(bar) } type SilverfinCompanyFoo struct { ID int `json:"id"` Name string `json:"name"` Vat string `json:"vat"` // here } type SilverfinCompanyBar struct { ID int `json:"id"` Name string `json:"name"` Vat string `json:"vat_identifier"` // here } // {1 Baz Qux}
This is a common solution for this type of scenario.
The above is the detailed content of Dynamically change json key when marshaling and unmarshaling. For more information, please follow other related articles on the PHP Chinese website!