Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]

validate json
Started by rootuid Aug 06 2018 02:46 PM

2 replies to this topic
This topic has been archived. This means that you cannot reply to this topic.
[TOPIC: post.html]


[GLOBAL: userInfoPane.html]
  • Observer

  • 21 posts
  • Corona SDK

I have a chunk of code that works just fine 

   if ( event.isError ) then 
        print( "Network error!")
        local newText = display.newText("Sorry, offline :(",150,10, "sega.ttf", 20)
        print ( "\n>>>>>>>>>>>>> Response from api : " .. event.response )
        local reply = display.newText(event.response,40, "sega.ttf", 25)

        local reply=  json.decode(event.response)

        for k, v in pairs(reply) do
            ---print( k, v )
            gold = v

The code however throws an exceptions when it doesn't get json back. Today my api was returning an internal server error in html and my code of course failed.


How can I validate that the reply was actually valid json? I don't see any validateJson() function in the json library/

[TOPIC: post.html]

XeduR @Spyric

[GLOBAL: userInfoPane.html]
XeduR @Spyric
  • Contributor

  • 842 posts
  • Corona SDK

You should be able to find your answer from the docs at https://docs.coronalabs.com/api/library/json/decode.html and related articles. Once you run json.decode, you could use " if not decoded then". 

[TOPIC: post.html]


[GLOBAL: userInfoPane.html]
  • Corona Geek

  • 1,348 posts
  • Enterprise

as per XeduR @Spyric, decode will return nil (and other info) if it fails to decode, and if nil then don't call pairs() on it.

(suspect you're getting an error, like "bad argument #1 to pairs, table expected, got nil", not an exception)