JSON Data Bug using httpservice fo the third time

I’m having this error message from this function whenever I call it

function GameFramework:AddToPlayerData(player, storeName, key, amount)
	local dataStore = self.DataStore[storeName]
	if not dataStore then
		warn("DataStore not initialized: " .. storeName)
		return
	end

	local success, err = pcall(function()

		local rawData = dataStore:GetAsync(player.UserId)
		local data = httpService:JSONDecode(rawData)
		print("Before update:", data)

		if type(data[key]) ~= "number" then
			data[key] = 0
		end
		data[key] = data[key] + amount
		print("After update:", data)

		local serializedData = httpService:JSONEncode(data)
		dataStore:SetAsync(player.UserId, serializedData)

		local dataFolder = player:FindFirstChild("data")
		if dataFolder then
			local valueInstance = dataFolder:FindFirstChild(key)
			if valueInstance and valueInstance:IsA("NumberValue") then
				valueInstance.Value = data[key]
			else
				local newValue = Instance.new("NumberValue")
				newValue.Name = key
				newValue.Value = data[key]
				newValue.Parent = dataFolder
			end
		end
	end)

	if not success then
		warn("Failed to add to data for player: " .. player.Name .. " - " .. err)
	end
end

The error message Is: argument #1 expects a string, but table was passed from this line:

local data = httpService:JSONDecode(rawData)

It tells you what the issue is, rawData is a table but JSONDecode expects a string. You can check what type rawData is or just omit the json decoding and encoding entirely because the datastoreservice methods do that for you anyway

1 Like