Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert json to array/map

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:

  • JSON.parse(...).map: Unexpected end of JSON input
  • JSON.parse(JSON.stringify(...)).map(...): data is displayed but I get an error: JSON.parse(...).map is not a function
  • Array(...).map: Each child in array or iterator should have a unique key.
like image 264
zappee Avatar asked Jan 17 '17 16:01

zappee


People also ask

Can we convert JSON to array?

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.

Can we convert JSON to map in Java?

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.

Can you map JSON?

You can't. The keys of a map can be anything, including objects. But JSON syntax only allows strings as keys.

Is a map a JSON object?

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.


1 Answers

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));
like image 72
Gary Avatar answered Oct 01 '22 16:10

Gary