I have a csv table which I converted into a json and want to parse this json in flutter based on conditional statements.
For example, first condition would be if the type is a planet and if the name matches the provided value then show the rest of the details in a list view like Charcs, Color and Distance.
Input would be just the type and name, so based on that I need to parse the json and extract the correct data.
Either I can have like 6 separate jsons for each type but it does not seem to be a good idea to me.
Any suggestions on how I can use conditional statements or maybe convert this json into a different format so that I can parse using indexes or elements in Flutter.
[
{
"Type": "Planet",
"Name": "Jupiter",
"Charcs": "Largest",
"Color": "blue",
"distance": "near"
},
{
"Type": "Planet",
"Name": "Earth",
"Charcs": "Inhabited",
"Color": "green",
"distance": "nearby"
},
{
"Type": "Planet",
"Name": "Mars",
"Charcs": "Red Planet",
"Color": "red",
"distance": "very near"
},
{
"Type": "Star",
"Name": "Polaris",
"Charcs": "abcddw",
"Color": "casc",
"distance": "far"
},
{
"Type": "Star",
"Name": "Sirius",
"Charcs": "qwqwd",
"Color": "asfaf",
"distance": "very far"
},
{
"Type": "Star",
"Name": "Betelgeuse",
"Charcs": "qwdwqeq",
"Color": "asfasfa",
"distance": "far far away"
}
]
CodePudding user response:
Because this is an array, you can use a loop that filters each item into a separate JSON key.
var array = [
{
"Type": "Planet",
"Name": "Jupiter",
"Charcs": "Largest",
"Color": "blue",
"distance": "near"
},
{
"Type": "Planet",
"Name": "Earth",
"Charcs": "Inhabited",
"Color": "green",
"distance": "nearby"
},
{
"Type": "Planet",
"Name": "Mars",
"Charcs": "Red Planet",
"Color": "red",
"distance": "very near"
},
{
"Type": "Star",
"Name": "Polaris",
"Charcs": "abcddw",
"Color": "casc",
"distance": "far"
},
{
"Type": "Star",
"Name": "Sirius",
"Charcs": "qwqwd",
"Color": "asfaf",
"distance": "very far"
},
{
"Type": "Star",
"Name": "Betelgeuse",
"Charcs": "qwdwqeq",
"Color": "asfasfa",
"distance": "far far away"
}
]
var json = {}
array.forEach(e => {
json[e.Type] ||= {}
json[e.Type][e.Name] = {Charcs: e.Charcs,Color: e.Color,distance:e.distance}
})
console.log(json)
The definition of the code above is the following:
json[e.Type] ||= {}
: This creates a key from the object type if it does not already existjson[e.Type][e.Name] = {Charcs: e.Charcs,Color: e.Color,distance:e.distance}
: This puts the data of the object in its own sub-key