Extract

Just starting out? Need help? Post your questions and find answers here.
Rjevsky
User
User
Posts: 23
Joined: Tue Jul 18, 2017 3:41 pm

Extract

Post by Rjevsky »

How extract this json to structure and read params "text" and "callback_data"?

Code: Select all

{
        "chat_id": "123456",
        "text": "Hi",
        "reply_markup": {
            "inline_keyboard": [[
                {
                    "text": "A",
                    "callback_data": "A1"            
                }, 
                {
                    "text": "B",
                    "callback_data": "C1"            
                }]
            ]
        }
    }

Code: Select all

Structure inline_keyboard
????
  text.s
   callback_data.s
EndStructure

Structure reply_markup_
Array inline_keyboard.inline_keyboard(1)
EndStructure

Structure msg
chat_id.s
text.s
reply_markup.reply_markup_
EndStructure
Olli
Addict
Addict
Posts: 1202
Joined: Wed May 27, 2020 12:26 pm

Re: Extract

Post by Olli »

The double symbol '[[' seems to add a deeper level...

Code: Select all

structure void
   text.s
   callback_data.s
endStructure

Structure inline_keyboard
  void.void
EndStructure

Structure reply_markup_
Array inline_keyboard.inline_keyboard(1)
EndStructure

Structure msg
chat_id.s
text.s
reply_markup.reply_markup_
EndStructure
infratec
Always Here
Always Here
Posts: 7588
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Extract

Post by infratec »

The problem is the unnamed List/Array inside of the JSON.

One possibility is:

Code: Select all

JSON$ = ~"{" + #LF$
JSON$ + ~" \"chat_id\": \"123456\"," + #LF$
JSON$ + ~" \"text\": \"Hi\"," + #LF$
JSON$ + ~" \"reply_markup\": {" + #LF$
JSON$ + ~"  \"inline_keyboard\": [" + #LF$
JSON$ + ~"   [" + #LF$
JSON$ + ~"    {" + #LF$
JSON$ + ~"     \"text\": \"A\"," + #LF$
JSON$ + ~"     \"callback_data\": \"A1\"" + #LF$
JSON$ + ~"    }," + #LF$
JSON$ + ~"    {" + #LF$
JSON$ + ~"    \"text\": \"B\"," + #LF$
JSON$ + ~"    \"callback_data\": \"C1\"" + #LF$
JSON$ + ~"    }" + #LF$
JSON$ + ~"   ]" + #LF$
JSON$ + ~"  ]" + #LF$
JSON$ + ~" }" + #LF$
JSON$ + ~"}"

Debug JSON$

JSON$ = RemoveString(JSON$, #CR$)
JSON$ = RemoveString(JSON$, #LF$)
JSON$ = RemoveString(JSON$, " ")

JSON$ = ReplaceString(JSON$, "[[", "[")
JSON$ = ReplaceString(JSON$, "]]", "]")

Debug JSON$

Structure inline_keyboard
  text.s
  callback_data.s
EndStructure

Structure reply_markup_
  List inline_keyboard.inline_keyboard()
EndStructure

Structure msg_structure
  chat_id.s
  text.s
  reply_markup.reply_markup_
EndStructure

Define msg.msg_structure

JSON = ParseJSON(#PB_Any, JSON$)
If JSON
  
  ExtractJSONStructure(JSONValue(JSON), @msg, msg_structure)
  
  Debug ""
  Debug msg\chat_id
  Debug msg\text
  ForEach msg\reply_markup\inline_keyboard()
    Debug msg\reply_markup\inline_keyboard()\text
    Debug msg\reply_markup\inline_keyboard()\callback_data
  Next
  
  FreeJSON(JSON)
EndIf
Post Reply