Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

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

2 replies to this topic
[TOPIC CONTROLS]
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

rootuid

[GLOBAL: userInfoPane.html]
rootuid
  • Observer

  • 19 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)
    else
        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
        end

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]
#2

XeduR @Spyric

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

  • 69 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]
#3

davebollinger

[GLOBAL: userInfoPane.html]
davebollinger
  • Corona Geek

  • 1,172 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)




[topic_controls]
[/topic_controls]