Add rows to UDataTable at runtime with c++ code

Would like to share how to add a row to a Data Table that is using blueprint structs.
Unfortunately this only works in editor and can’t do a packaged build with it.
In the header file:

	UFUNCTION(BlueprintCallable, BlueprintNativeEvent, meta = (CustomStructureParam = "Struct"))
	void AddToDataTable(UDataTable* inDatatable, FName inRowName, const FString& JsonStructString);

	UFUNCTION(BlueprintCallable, BlueprintNativeEvent)
	void RemoveDataTableRow(UDataTable* inDatatable, FName inRowName);

In the C++ file

void U::AddToDataTable_Implementation(UDataTable* inDatatable, FName inRowName,const FString& JsonStructString)
{
	FString localDatabaseString = inDatatable->GetTableAsJSON();
	FString localJsonStruct = JsonStructString;

	localDatabaseString.RemoveAt(localDatabaseString.Len()-1,1,true);
	localJsonStruct.RemoveAt(0,1,true);

	localJsonStruct = ",{\"Name\": \"" + inRowName.ToString() + "\"," + localJsonStruct;
	localDatabaseString = localDatabaseString + localJsonStruct + "]";
	
	inDatatable->CreateTableFromJSONString(localDatabaseString);
}

void U::RemoveDataTableRow_Implementation(UDataTable* inDatatable, FName inRowName)
{
	inDatatable->RemoveRow(inRowName);
}

Screenshot 2024-02-16 145305

Just enable Json Blueprint Utilities Plugin

1 Like