Skip to content
Advertisement

Converting CSV to JSON using JavaScript

I’m learning JavaScript and i’m trying to convert a CSV file to a JSON.

The structure of my csv is :

Name Class region_count Coordinates
foto_4.jpeg soccer 1 “all_points_x”:[90,80,77,74,82,89,113,142,146,153,162,174,184,199,220,235,261,280,289,298,298,287,279,276,271,268,265,266,270,270,262,249,236,222,213,188,170,151,114,92],”all_points_y”:[145,171,192,211,241,263,291,308,310,301,288,275,265,257,246,244,241,238,241,243,235,223,208,196,176,165,148,134,119,114,109,99,96,93,90,89,89,94,116,146]
foto_4.jpeg tennis 2 “all_points_x”:[394,418,445,456,467,472,469,461,448,436,425,412,402,394,384,383,392],”all_points_y”:[276,259,260,266,279,296,313,327,335,341,342,338,334,326,313,294,279]
foto_5.jpeg basket 1 “all_points_x”:[345,373,427,479,509,540,553,549,541,526,490,467,455,447,430,421,411,406,400,394,391,381,368,349,337,327,320,308,301],”all_points_y”:[23,11,7,22,44,89,140,182,207,230,261,274,263,260,255,255,255,261,268,273,278,286,279,273,268,258,250,242,237]

the desired json structure is:

JavaScript

I tried to convert this CSV to JSON with this code

JavaScript

the JSON create is this:

JavaScript

With my code I can’t iterate for all the polygons contained in one picture and I can’t add region key (example region) that contains other keys

How can I reach my desired output?

Advertisement

Answer

Your initial approach looks pretty good. We just need some more modifications to the data you generated. Instead of directly mapping each row to JSON, first keep data in the array as a line item, and then build the JSON data as follows.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement