FromJSON

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

This function parses a JSON formatted string and unpacks the values into Lua variables. You can use toJSON to encode variables into a JSON string that can be read by this function.


[[{{{image}}}|link=|]] Important Note: When parsing a JSON array, fromJSON unpacks the elements as multiple separate values. To mimic standard JSON parsing behavior and store these elements together in a single Lua table, you must wrap the function call in a table constructor {}.

If your JSON string was generated directly by toJSON, you do not need to wrap it.

local jsonString = '["Apple", "Orange"]'
local fruitsTable = { fromJSON(jsonString) }

Syntax

var... fromJSON ( string json )

Required Arguments

  • json: A JSON formatted string.

Returns

Returns the parsed JSON data as multiple values or a single table depending on the input JSON structure:

  • Returns multiple separate values (unpacked) if the root element of the JSON is an array
  • Returns a table if the root element of the JSON is an object
  • Returns nil if the JSON string is invalid or malformed.

Examples

Example 1: Assigning to multiple variables

This example shows how fromJSON extracts values from a JSON array directly into separate Lua variables.

local jsonArray = '["Desert Eagle", 24]'

local name, ammo = fromJSON(jsonArray)

print(name, ammo) --> Output: Desert Eagle  24

Example 2: Wrapping the call inside a table

This example shows how to capture all values of a JSON array in a single Lua table.

local jsonArray = '["Apple", "Orange", "Banana"]'

-- Put the fromJSON call inside of a table directly to capture all the values of the JSON array
local fruits = {fromJSON(jsonArray)}

if fruits[1] then -- Make sure the JSON was parsed correctly
    for i=1, #fruits do
        print(fruits[i])
    end
    --[[ Output:
    Apple
    Orange
    Banana
    ]]
end

Example 3: Parsing a JSON object

local jsonObject = '{"playerName": "Alex", "score": 2500}'

local playerStats = fromJSON(jsonObject)

if playerStats then
    print(playerStats.playerName) --> Output: Alex
    print(playerStats.score)      --> Output: 2500
end

Example 4: Parsing a nested JSON object

local jsonString = '{"vehicle": "Infernus", "upgrades": {"nos": true, "paintjob": 2}}'

local vehicleInfo = fromJSON(jsonString)

if vehicleInfo then
    print(vehicleInfo.vehicle)           --> Output: Infernus
    print(vehicleInfo.upgrades.nos)      --> Output: true
    print(vehicleInfo.upgrades.paintjob) --> Output: 2
end

See Also