Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

JSON is printing nil instead of a string? [closed]

I'm trying to decode this JSON:

[{"ModName":"MainBase","Pos":{"Z":-13,"X":-7,"Y":0},"Rot":{"Z":0,"X":0,"Y":0}}]

Here is the problem using this line:

local HttpService = game:GetService("HttpService")
local DecodedJSON = HttpService:JSONDecode(ToDecodeJSON)

for number, tab in pairs (DecodedJSON) do
	local Current = tab["ModName"]
	print(tab)
end

And it prints nil instead of MainBase because the original table was:

local ATable = {ModName = "MainBase"} -- Other stuff behind

Well it doesn't print MainBase but nil.

2 answers

[{"ModName":"MainBase","Pos":{"Z":-13,"X":-7,"Y":0},"Rot":{"Z":0,"X":0,"Y":0}}]
---
local ATable = {ModName = "MainBase"} print(ATable.ModName)

You want to use it like that basically.

JSONDecode it, and just get the ModName like that. but you will need to loop for position. OR do

print(DecodeJSON.Pos[1])

Please accept my answer if it helped!!

2 comments

0

Thanks for the answer! :D But I can't accept it because I have 2 good answers, I added a +1 vote instead.

0

Thank you :-)

I don't seem to have any problem with printing the table:-

local json = '[{"ModName":"MainBase","Pos":{"Z":-13,"X":-7,"Y":0},"Rot":{"Z":0,"X":0,"Y":0}}]'
local HttpService = game:GetService("HttpService")
local DecodedJSON = HttpService:JSONDecode(json)

function unpackTable(tbl)
	for i, v in pairs (tbl) do
	    if type(v) == 'table' then
			unpackTable(v) -- recursive  loop
		else
			print(i,v)
		end
	end
end

unpackTable(DecodedJSON)

output:-

Y 0

X 0

Z 0

ModName MainBase

Y 0

X -7

Z -13

The problem is the table you have wrapped around e.g. the '[ ]' which is converted to another table

local json = '[{"ModName":"MainBase","Pos":{"Z":-13,"X":-7,"Y":0},"Rot":{"Z":0,"X":0,"Y":0}}]'
local HttpService = game:GetService("HttpService")
local DecodedJSON = HttpService:JSONDecode(json)

print(unpack(DecodedJSON)['ModName']) -- unpack will unpack the table which holds another table that holds the data
print(DecodedJSON[1]['ModName']) -- or you can just access the 1st table 
print(type(DecodedJSON), 'num', #DecodedJSON)

output:-

MainBase

MainBase

table numb 1

Hope this help, pls comment if you need help with this code.

1 comment

0

Thanks for the answer! :D But I can't accept it because I have 2 good answers, I added a +1 vote instead. Well, the unpack() function it very useful, thanks a lot :D

This discussion is preserved as it was. New answers, comments, and votes are closed.