My rest API returns with the following json content:
[{
"key": "apple",
"value": "green"
},
{
"key": "banana",
"value": "yellow"
}]
I am iterating through the list with this code:
this.props.json.map(row => {
return <RowRender key={id.row} row={row} />
}
It works because the content is displayed but on the web browser's console I can see an error:
map is not a function
I googled for it and I changed my code to this:
Array.prototype.slice.call(this.props.json).map(row => {
return <RowRender key={id.row} row={row} />
}
It works without any error but seems so complicated. Is that the correct way to do this job?
UPDATE
What I tried:
Convert JSON to Array Using `json. The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string. Make sure that it has a string value coming from a server or the local source.
We can easily convert JSON data into a map because the JSON format is essentially a key-value pair grouping and the map also stores data in key-value pairs. Let's understand how we can use both JACKSON and Gson libraries to convert JSON data into a Map.
You can't. The keys of a map can be anything, including objects. But JSON syntax only allows strings as keys.
A JSONObject is an unordered collection of name/value pairs whereas Map is an object that maps keys to values. A Map cannot contain duplicate keys and each key can map to at most one value. We need to use the JSON-lib library for serializing and de-serializing a Map in JSON format.
Use Object.entries()
to get both the key and values, then give that to Map()
to allow you to select your values by key.
let myMap = new Map(Object.entries(this.props.json));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With