This is my input and I want a function for converting it to an object:
var filecontent = "22,david\n" + "25,jack\n" + "19,jason\n" + "18,peter\n";
How can I convert it to this object?
let obj = {
"22":"david",
"25":"jack",
"19":"jason",
"18":"peter"
}
try this
var filecontent = "22,david\n" + "25,jack\n" + "19,jason\n" + "18,peter\n";
replace all ,
and \n
to make it a json format
filecontent = filecontent.replaceAll(",",'":"').replaceAll("\n",'","')
remove the extra characters from the string
filecontent= filecontent.substring(0, filecontent.length - 2);
add the missing {"
, }
to make a valid json
filecontent='{"'+filecontent+'}';
the using JSON.parse to convert the string to obj
var obj = JSON.parse(filecontent);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.