JSON: Adding new object members during parsing
This example shows how to use the reviver parameter in JSON.parse to add new object members and format existing members during the parsing phase.
Choose a currency, then get the data
| SKU | Item | Price (USD) | Price (USD) |
|---|---|---|---|
| Click Get Data | |||
The data
The data returned from the server will be a JSON string containing this object structure:
Create a reviver function
We'll contain all the moving parts in an example namespace. In it, we'll include the currency exchange rates and a function to reference the rates to add a new member to the JSON response as it is being parsed.
Sending the request and parsing the JSON response
When the Get Data button is clicked, we send an io request for the JSON data, and in our success handler, pass our conversion function to JSON.parse with the response text. The resulting inventory records will have an additional member, convertedPrice. This data is then passed to a UI method to update the inventory table.
Example markup
Full Code Listing
Below is the full source for the example, including the functions responsible for formatting the price and updating the UI.
