XLSX Serialize/Deserialize

Discuss about plugins that don't have a dedicated forum
Post Reply
User avatar
Lerio69
Posts: 29
Joined: Sat Sep 24, 2016 11:47 pm
Location: Italy

XLSX Serialize/Deserialize

Post by Lerio69 »

I try to convert a Json file into XLSX file, for to do this i create this simple function

Code: Select all

Function p_SaveXLSX()
	Local f$ = moai.Get("file", "text")
	Local mTable = {}

	If f$ <>""
		;convert json file into table
		mTable = DeserializeTable(FileToString(f$), "Default")		
		
		;convert table into XLSX file
		Local fname$ = UnleftStr(FilePart(f$), 5)..".xlsx"
		Local s$ = FileRequest("Save XLSX", {Filters="xlsx", Mode=#REQ_SAVEMODE, File=fname$})	
		;StringToFile(SerializeTable(mTable, "xlsx"), s$)
		OpenFile(1, s$, #MODE_WRITE)
			WriteTable(1, mTable, {Adapter="xlsx"})
		CloseFile(1)
	EndIf
EndFunction
I always get "Error serializing item!" error when a table is created from a json file.

This is a json that i need to convert:

Code: Select all

{
	"mod_name": "MOD Test 2020",
	"mod_url": "http://filedn.eu/lM8guATtwL9pUR2zqpEfSVF/mod1/files",
	"mod_version": "1.00",
	"mod_date": "03/07/2020"
}
User avatar
airsoftsoftwair
Posts: 5446
Joined: Fri Feb 12, 2010 2:33 pm
Location: Germany
Contact:

Re: XLSX Serialize/Deserialize

Post by airsoftsoftwair »

This can't work because the XLSX plugin expects the table to be in a different format, as described here. XLSX documents can't contain whole trees of data but just a number of columns and rows. Thus, you have to make sure you pass a 2D table that reflects such a column-row layout. Here's how to do what you want:

Code: Select all

f$ = "test.json"
mTable = DeserializeTable(FileToString(f$), "Default")	
t = {}	
For i,v In Pairs(mTable)
   t[n] = {i, v}	
   n = n + 1
Next	
Local fname$ = UnleftStr(f$, 5)..".xlsx"
StringToFile(SerializeTable(t, "xlsx"), fname$)
Of course, this will only work with JSON files that have a layout like the one you posted. It's not possible to serialize arbitrary JSONs to XLSX because not everything in JSON can be represented in an XLSX.
User avatar
Lerio69
Posts: 29
Joined: Sat Sep 24, 2016 11:47 pm
Location: Italy

Re: XLSX Serialize/Deserialize

Post by Lerio69 »

Ok thanks, i need a lot of work to convert json that i want :lol:
Post Reply