mergJSONEncode

Typefunction
DictionaryLCS
LibraryLiveCode Script
Syntax
mergJSONEncode(<pVariableName>, [<pForceRootType>, <pPretty>])
Associationsmergjson
Summary

The function encodes an array as JSON.

Introduced8.0
OSios, android, linux, mac, windows
Platformsmobile, desktop, server
Parameters
NameTypeDescription
pVariableName

The name of the variable to encode as JSON. All strings must be UTF8 encoded.

pForceRootType

The root type for JSON conversion may be forced using this optional parameter. In the case of a numerically and sequentially keyed array starting from 1 the array will be encoded as an ordered list in JSON. Use object as the parameter value to force the array to be encoded as an object instead. In some cases when encoding scalar variables a number (or something that looks like a number) might need to be encoded as a string. Use string as the parameter value to force the number to be encoded as a string instead.

pPretty

Use this optional parameter which defaults to false to pretty print the JSON. If true the JSON will formatted with whitespace and object names will be alphabetically sorted.

Example
function ArrayToJSON pArray,pForceRootType,pPretty
    repeat for each key tKey in pArray
        if pArray[tKey] is an array then
            put "}"&ArrayToJSON(pArray[tKey]) into pArray[tKey]
        end if
    end repeat
    return(mergJSONEncode("pArray",pForceRootType,pPretty))
end ArrayToJSON
Values
NameTypeDescription
return

The array encoded as JSON.

Description

If the external encounters } as the first char of an array element it will assume the string is already encoded. This is how the recursive function is able to translate a multi-dimensional array into JSON. It's also the only way to get an empty array or object into your JSON by setting the element value to }[] or }{}.

If a value looks like a real number it is encoded as an IEEE 754 double. In order to represent the number uniquely a double may need a precision of 15 to 17 decimal places. What this means is that any encoded then decoded doubles may need to be formatted or rounded to the precision you require before displaying it to a user because something like 0.657679 when converted to a double will become 0.65767900000000001.

Tagsexternals