Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by 7 years ago
Edited 7 years ago

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

Log in to vote
1
Answered by
ikiled 75 Donator
7 years ago
[{"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!!

0
Thanks for the answer! :D But I can't accept it because I have 2 good answers, I added a +1 vote instead. maquilaque 136 — 7y
0
Thank you :-) ikiled 75 — 7y
Ad
Log in to vote
1
Answered by 7 years ago
Edited 7 years ago

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.

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 maquilaque 136 — 7y

Answer this question