-1

Hello I have lua nginx and I'm having request body

My POST body is this :

{
    "param1": "1033893",
    "param2": "337483",
    "param3": "test",
    
}

I want to cut only param2 and make it a variable, then match it with a file which it's having lines that contain numbers like this.

If it's found then I should call another command

Update 1 :

I'm using

local check_body = ngx.req.get_body_data()

Update 2:

In bash I'm using this to cut the part and value of param2

echo $CURL_post_request | cut -d\| -f 1| grep -m1  -oP '\s*"param2"\s*:\s*\K[^,]+'| tr -d '"'| tr -d '}'

But in lua I'm not sure how to cut and put as variable?

Vancho
  • 25
  • 7
  • Don't use patterns / RegEx to extract data from JSON. Instead, use a proper JSON parser, then extract the fields you need. – Luatic Mar 02 '23 at 08:43
  • @LMD can you give me a proper example? – Vancho Mar 02 '23 at 09:01
  • Look into e.g. [json.lua](https://github.com/rxi/json.lua/). It's pretty easy to use. – Luatic Mar 02 '23 at 09:05
  • Hello @LMD thanks very much, I'm a little beginner with Lua, so I'm getting the following encode the response ` "{\r\n \"param1\": \"1033893\",\r\n \"param2\": \"337483\",\r\n \"param3\": \"test\",\r\n \"param4\": \"542722\",\r\n \"param5\": 5,\r\n \"param6\": {\r\n \"status\": \"Success\"\r\n },\r\n \"resultData\": null\r\n}" ` But if I use it to decode I get this in my error log ` bad argument #1 to 'say' (non-array table found) ` Also what do you prefer for cutting param2 value? – Vancho Mar 02 '23 at 10:02
  • Hi again @LMD I'm using ` json = require "json" local json_parse = json.encode(check_body) local param2_cut = json_parse.param2 ngx.say(iccid_cut) ` – Vancho Mar 02 '23 at 10:11
  • you need to use `json.decode` – Luatic Mar 02 '23 at 12:30

1 Answers1

0

I've been using another module http://dkolf.de/src/dkjson-lua.fsl/home

First i'm doing adding entry to nginx.conf

lua_package_path "/usr/local/openresty/lualib/?.lua;;";


  json = require "dkjson"
   local json_parse = json.decode(check_body)
   local iccid_cut = json_parse.param2
Vancho
  • 25
  • 7