FromJSON: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
mNo edit summary
mNo edit summary
 
(No difference)

Latest revision as of 02:12, 9 June 2026

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 parse 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 single 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"]'

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

print(fruits[1], fruits[2]) --> Output: Apple  Orange

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