class_json.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. :github_url: hide
  2. .. DO NOT EDIT THIS FILE!!!
  3. .. Generated automatically from Godot engine sources.
  4. .. Generator: https://github.com/godotengine/godot/tree/master/doc/tools/make_rst.py.
  5. .. XML source: https://github.com/godotengine/godot/tree/master/doc/classes/JSON.xml.
  6. .. _class_JSON:
  7. JSON
  8. ====
  9. **Inherits:** :ref:`Resource<class_Resource>` **<** :ref:`RefCounted<class_RefCounted>` **<** :ref:`Object<class_Object>`
  10. Helper class for creating and parsing JSON data.
  11. .. rst-class:: classref-introduction-group
  12. Description
  13. -----------
  14. The **JSON** class enables all data types to be converted to and from a JSON string. This is useful for serializing data, e.g. to save to a file or send over the network.
  15. \ :ref:`stringify()<class_JSON_method_stringify>` is used to convert any data type into a JSON string.
  16. \ :ref:`parse()<class_JSON_method_parse>` is used to convert any existing JSON data into a :ref:`Variant<class_Variant>` that can be used within Godot. If successfully parsed, use :ref:`data<class_JSON_property_data>` to retrieve the :ref:`Variant<class_Variant>`, and use :ref:`@GlobalScope.typeof()<class_@GlobalScope_method_typeof>` to check if the Variant's type is what you expect. JSON Objects are converted into a :ref:`Dictionary<class_Dictionary>`, but JSON data can be used to store :ref:`Array<class_Array>`\ s, numbers, :ref:`String<class_String>`\ s and even just a boolean.
  17. ::
  18. var data_to_send = ["a", "b", "c"]
  19. var json_string = JSON.stringify(data_to_send)
  20. # Save data
  21. # ...
  22. # Retrieve data
  23. var json = JSON.new()
  24. var error = json.parse(json_string)
  25. if error == OK:
  26. var data_received = json.data
  27. if typeof(data_received) == TYPE_ARRAY:
  28. print(data_received) # Prints the array.
  29. else:
  30. print("Unexpected data")
  31. else:
  32. print("JSON Parse Error: ", json.get_error_message(), " in ", json_string, " at line ", json.get_error_line())
  33. Alternatively, you can parse strings using the static :ref:`parse_string()<class_JSON_method_parse_string>` method, but it doesn't handle errors.
  34. ::
  35. var data = JSON.parse_string(json_string) # Returns null if parsing failed.
  36. \ **Note:** Both parse methods do not fully comply with the JSON specification:
  37. - Trailing commas in arrays or objects are ignored, instead of causing a parser error.
  38. - New line and tab characters are accepted in string literals, and are treated like their corresponding escape sequences ``\n`` and ``\t``.
  39. - Numbers are parsed using :ref:`String.to_float()<class_String_method_to_float>` which is generally more lax than the JSON specification.
  40. - Certain errors, such as invalid Unicode sequences, do not cause a parser error. Instead, the string is cleaned up and an error is logged to the console.
  41. .. rst-class:: classref-reftable-group
  42. Properties
  43. ----------
  44. .. table::
  45. :widths: auto
  46. +-------------------------------+---------------------------------------+----------+
  47. | :ref:`Variant<class_Variant>` | :ref:`data<class_JSON_property_data>` | ``null`` |
  48. +-------------------------------+---------------------------------------+----------+
  49. .. rst-class:: classref-reftable-group
  50. Methods
  51. -------
  52. .. table::
  53. :widths: auto
  54. +---------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  55. | :ref:`Variant<class_Variant>` | :ref:`from_native<class_JSON_method_from_native>`\ (\ variant\: :ref:`Variant<class_Variant>`, full_objects\: :ref:`bool<class_bool>` = false\ ) |static| |
  56. +---------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  57. | :ref:`int<class_int>` | :ref:`get_error_line<class_JSON_method_get_error_line>`\ (\ ) |const| |
  58. +---------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  59. | :ref:`String<class_String>` | :ref:`get_error_message<class_JSON_method_get_error_message>`\ (\ ) |const| |
  60. +---------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  61. | :ref:`String<class_String>` | :ref:`get_parsed_text<class_JSON_method_get_parsed_text>`\ (\ ) |const| |
  62. +---------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  63. | :ref:`Error<enum_@GlobalScope_Error>` | :ref:`parse<class_JSON_method_parse>`\ (\ json_text\: :ref:`String<class_String>`, keep_text\: :ref:`bool<class_bool>` = false\ ) |
  64. +---------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  65. | :ref:`Variant<class_Variant>` | :ref:`parse_string<class_JSON_method_parse_string>`\ (\ json_string\: :ref:`String<class_String>`\ ) |static| |
  66. +---------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  67. | :ref:`String<class_String>` | :ref:`stringify<class_JSON_method_stringify>`\ (\ data\: :ref:`Variant<class_Variant>`, indent\: :ref:`String<class_String>` = "", sort_keys\: :ref:`bool<class_bool>` = true, full_precision\: :ref:`bool<class_bool>` = false\ ) |static| |
  68. +---------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  69. | :ref:`Variant<class_Variant>` | :ref:`to_native<class_JSON_method_to_native>`\ (\ json\: :ref:`Variant<class_Variant>`, allow_objects\: :ref:`bool<class_bool>` = false\ ) |static| |
  70. +---------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  71. .. rst-class:: classref-section-separator
  72. ----
  73. .. rst-class:: classref-descriptions-group
  74. Property Descriptions
  75. ---------------------
  76. .. _class_JSON_property_data:
  77. .. rst-class:: classref-property
  78. :ref:`Variant<class_Variant>` **data** = ``null`` :ref:`🔗<class_JSON_property_data>`
  79. .. rst-class:: classref-property-setget
  80. - |void| **set_data**\ (\ value\: :ref:`Variant<class_Variant>`\ )
  81. - :ref:`Variant<class_Variant>` **get_data**\ (\ )
  82. Contains the parsed JSON data in :ref:`Variant<class_Variant>` form.
  83. .. rst-class:: classref-section-separator
  84. ----
  85. .. rst-class:: classref-descriptions-group
  86. Method Descriptions
  87. -------------------
  88. .. _class_JSON_method_from_native:
  89. .. rst-class:: classref-method
  90. :ref:`Variant<class_Variant>` **from_native**\ (\ variant\: :ref:`Variant<class_Variant>`, full_objects\: :ref:`bool<class_bool>` = false\ ) |static| :ref:`🔗<class_JSON_method_from_native>`
  91. Converts a native engine type to a JSON-compliant value.
  92. By default, objects are ignored for security reasons, unless ``full_objects`` is ``true``.
  93. You can convert a native value to a JSON string like this:
  94. ::
  95. func encode_data(value, full_objects = false):
  96. return JSON.stringify(JSON.from_native(value, full_objects))
  97. .. rst-class:: classref-item-separator
  98. ----
  99. .. _class_JSON_method_get_error_line:
  100. .. rst-class:: classref-method
  101. :ref:`int<class_int>` **get_error_line**\ (\ ) |const| :ref:`🔗<class_JSON_method_get_error_line>`
  102. Returns ``0`` if the last call to :ref:`parse()<class_JSON_method_parse>` was successful, or the line number where the parse failed.
  103. .. rst-class:: classref-item-separator
  104. ----
  105. .. _class_JSON_method_get_error_message:
  106. .. rst-class:: classref-method
  107. :ref:`String<class_String>` **get_error_message**\ (\ ) |const| :ref:`🔗<class_JSON_method_get_error_message>`
  108. Returns an empty string if the last call to :ref:`parse()<class_JSON_method_parse>` was successful, or the error message if it failed.
  109. .. rst-class:: classref-item-separator
  110. ----
  111. .. _class_JSON_method_get_parsed_text:
  112. .. rst-class:: classref-method
  113. :ref:`String<class_String>` **get_parsed_text**\ (\ ) |const| :ref:`🔗<class_JSON_method_get_parsed_text>`
  114. Return the text parsed by :ref:`parse()<class_JSON_method_parse>` (requires passing ``keep_text`` to :ref:`parse()<class_JSON_method_parse>`).
  115. .. rst-class:: classref-item-separator
  116. ----
  117. .. _class_JSON_method_parse:
  118. .. rst-class:: classref-method
  119. :ref:`Error<enum_@GlobalScope_Error>` **parse**\ (\ json_text\: :ref:`String<class_String>`, keep_text\: :ref:`bool<class_bool>` = false\ ) :ref:`🔗<class_JSON_method_parse>`
  120. Attempts to parse the ``json_text`` provided.
  121. Returns an :ref:`Error<enum_@GlobalScope_Error>`. If the parse was successful, it returns :ref:`@GlobalScope.OK<class_@GlobalScope_constant_OK>` and the result can be retrieved using :ref:`data<class_JSON_property_data>`. If unsuccessful, use :ref:`get_error_line()<class_JSON_method_get_error_line>` and :ref:`get_error_message()<class_JSON_method_get_error_message>` to identify the source of the failure.
  122. Non-static variant of :ref:`parse_string()<class_JSON_method_parse_string>`, if you want custom error handling.
  123. The optional ``keep_text`` argument instructs the parser to keep a copy of the original text. This text can be obtained later by using the :ref:`get_parsed_text()<class_JSON_method_get_parsed_text>` function and is used when saving the resource (instead of generating new text from :ref:`data<class_JSON_property_data>`).
  124. .. rst-class:: classref-item-separator
  125. ----
  126. .. _class_JSON_method_parse_string:
  127. .. rst-class:: classref-method
  128. :ref:`Variant<class_Variant>` **parse_string**\ (\ json_string\: :ref:`String<class_String>`\ ) |static| :ref:`🔗<class_JSON_method_parse_string>`
  129. Attempts to parse the ``json_string`` provided and returns the parsed data. Returns ``null`` if parse failed.
  130. .. rst-class:: classref-item-separator
  131. ----
  132. .. _class_JSON_method_stringify:
  133. .. rst-class:: classref-method
  134. :ref:`String<class_String>` **stringify**\ (\ data\: :ref:`Variant<class_Variant>`, indent\: :ref:`String<class_String>` = "", sort_keys\: :ref:`bool<class_bool>` = true, full_precision\: :ref:`bool<class_bool>` = false\ ) |static| :ref:`🔗<class_JSON_method_stringify>`
  135. Converts a :ref:`Variant<class_Variant>` var to JSON text and returns the result. Useful for serializing data to store or send over the network.
  136. \ **Note:** The JSON specification does not define integer or float types, but only a *number* type. Therefore, converting a Variant to JSON text will convert all numerical values to :ref:`float<class_float>` types.
  137. \ **Note:** If ``full_precision`` is ``true``, when stringifying floats, the unreliable digits are stringified in addition to the reliable digits to guarantee exact decoding.
  138. The ``indent`` parameter controls if and how something is indented; its contents will be used where there should be an indent in the output. Even spaces like ``" "`` will work. ``\t`` and ``\n`` can also be used for a tab indent, or to make a newline for each indent respectively.
  139. \ **Example output:**\
  140. ::
  141. ## JSON.stringify(my_dictionary)
  142. {"name":"my_dictionary","version":"1.0.0","entities":[{"name":"entity_0","value":"value_0"},{"name":"entity_1","value":"value_1"}]}
  143. ## JSON.stringify(my_dictionary, "\t")
  144. {
  145. "name": "my_dictionary",
  146. "version": "1.0.0",
  147. "entities": [
  148. {
  149. "name": "entity_0",
  150. "value": "value_0"
  151. },
  152. {
  153. "name": "entity_1",
  154. "value": "value_1"
  155. }
  156. ]
  157. }
  158. ## JSON.stringify(my_dictionary, "...")
  159. {
  160. ..."name": "my_dictionary",
  161. ..."version": "1.0.0",
  162. ..."entities": [
  163. ......{
  164. ........."name": "entity_0",
  165. ........."value": "value_0"
  166. ......},
  167. ......{
  168. ........."name": "entity_1",
  169. ........."value": "value_1"
  170. ......}
  171. ...]
  172. }
  173. .. rst-class:: classref-item-separator
  174. ----
  175. .. _class_JSON_method_to_native:
  176. .. rst-class:: classref-method
  177. :ref:`Variant<class_Variant>` **to_native**\ (\ json\: :ref:`Variant<class_Variant>`, allow_objects\: :ref:`bool<class_bool>` = false\ ) |static| :ref:`🔗<class_JSON_method_to_native>`
  178. Converts a JSON-compliant value that was created with :ref:`from_native()<class_JSON_method_from_native>` back to native engine types.
  179. By default, objects are ignored for security reasons, unless ``allow_objects`` is ``true``.
  180. You can convert a JSON string back to a native value like this:
  181. ::
  182. func decode_data(string, allow_objects = false):
  183. return JSON.to_native(JSON.parse_string(string), allow_objects)
  184. .. |virtual| replace:: :abbr:`virtual (This method should typically be overridden by the user to have any effect.)`
  185. .. |const| replace:: :abbr:`const (This method has no side effects. It doesn't modify any of the instance's member variables.)`
  186. .. |vararg| replace:: :abbr:`vararg (This method accepts any number of arguments after the ones described here.)`
  187. .. |constructor| replace:: :abbr:`constructor (This method is used to construct a type.)`
  188. .. |static| replace:: :abbr:`static (This method doesn't need an instance to be called, so it can be called directly using the class name.)`
  189. .. |operator| replace:: :abbr:`operator (This method describes a valid operator to use with this type as left-hand operand.)`
  190. .. |bitfield| replace:: :abbr:`BitField (This value is an integer composed as a bitmask of the following flags.)`
  191. .. |void| replace:: :abbr:`void (No return value.)`