Home > OS >  How to parse a string received via a get request using form2Json?
How to parse a string received via a get request using form2Json?

Time:11-24

I get the error

SyntaxError: Unexpected token: in JSON at position 5759 (line 42)

on the first request, and on the second everything is fine, what could be the problem and how can it be solved?

function myFunction() {
var one = "leads[update][0][id]=30896454&leads[update][0][name]=Дарья (Алина) 23.11.2021 12:30&leads[update][0][status_id]=33131353&leads[update][0][old_status_id]=33131347&leads[update][0][price]=0&leads[update][0][responsible_user_id]=7490283&leads[update][0][last_modified]=1637662097&leads[update][0][modified_user_id]=0&leads[update][0][created_user_id]=0&leads[update][0][date_create]=1636435650&leads[update][0][pipeline_id]=1635139&leads[update][0][tags][0][id]=451580&leads[update][0][tags][0][name]=tilda&leads[update][0][tags][1][id]=469607&leads[update][0][tags][1][name]=Вводное&leads[update][0][tags][2][id]=475269&leads[update][0][tags][2][name]=Партнерка&leads[update][0][tags][3][id]=476169&leads[update][0][tags][3][name]=онлайн-занятия&leads[update][0][tags][4][id]=480372&leads[update][0][tags][4][name]=ВУ&leads[update][0][tags][5][id]=483228&leads[update][0][tags][5][name]=Акция +2&leads[update][0][tags][6][id]=485614&leads[update][0][tags][6][name]=Откладывают&leads[update][0][tags][7][id]=486524&leads[update][0][tags][7][name]=Звук «Л»&leads[update][0][tags][8][id]=486530&leads[update][0][tags][8][name]=Логопедия&leads[update][0][tags][9][id]=487240&leads[update][0][tags][9][name]=ПК&leads[update][0][tags][10][id]=490756&leads[update][0][tags][10][name]=Чтение&leads[update][0][tags][11][id]=493262&leads[update][0][tags][11][name]=неделя в подарок&leads[update][0][account_id]=24809335&leads[update][0][custom_fields][0][id]=683303&leads[update][0][custom_fields][0][name]=utm_referrer&leads[update][0][custom_fields][0][code]=UTM_REFERRER&leads[update][0][custom_fields][1][id]=681646&leads[update][0][custom_fields][1][name]=Сотрудник, Yclients&leads[update][0][custom_fields][1][values][0][value]=Гавриченко Дарья&leads[update][0][custom_fields][2][id]=681648&leads[update][0][custom_fields][2][name]=Длительность процедуры, Yclients&leads[update][0][custom_fields][2][values][0][value]=45 мин.&leads[update][0][custom_fields][3][id]=928932&leads[update][0][custom_fields][3][name]=Менеджер 1 линии&leads[update][0][custom_fields][3][values][0][value]=Гусева Наталия&leads[update][0][custom_fields][3][values][0][enum]=4204978&leads[update][0][custom_fields][4][id]=678201&leads[update][0][custom_fields][4][name]=Регион&leads[update][0][custom_fields][4][values][0][value]=Тверская область&leads[update][0][custom_fields][5][id]=913962&leads[update][0][custom_fields][5][name]=Возраст ребенка&leads[update][0][custom_fields][5][values][0][value]=6&leads[update][0][custom_fields][5][values][0][enum]=4198694&leads[update][0][custom_fields][6][id]=681336&leads[update][0][custom_fields][6][name]=Онлайн Категории&leads[update][0][custom_fields][6][values][0][value]=Звукопроизношение&leads[update][0][custom_fields][6][values][0][enum]=4188232&leads[update][0][custom_fields][7][id]=673089&leads[update][0][custom_fields][7][name]=ID записи, Yclients&leads[update][0][custom_fields][7][values][0][value]=290330-375075392&leads[update][0][custom_fields][8][id]=673093&leads[update][0][custom_fields][8][name]=Дата записи, Yclients&leads[update][0][custom_fields][8][values][0][value]=23.11.2021&leads[update][0][custom_fields][9][id]=673091&leads[update][0][custom_fields][9][name]=Время записи, Yclients&leads[update][0][custom_fields][9][values][0][value]=12:30&leads[update][0][custom_fields][10][id]=928936&leads[update][0][custom_fields][10][name]=Требует дозвона (Т)&leads[update][0][custom_fields][10][values][0]=1636405200&leads[update][0][custom_fields][11][id]=928940&leads[update][0][custom_fields][11][name]=Подтвердили ВУ (Т)&leads[update][0][custom_fields][11][values][0]=1637528400&leads[update][0][custom_fields][12][id]=928942&leads[update][0][custom_fields][12][name]=Занятие прошло (Т)&leads[update][0][custom_fields][12][values][0]=1637614800&leads[update][0][custom_fields][13][id]=928944&leads[update][0][custom_fields][13][name]=Записан на пробное (Т)&leads[update][0][custom_fields][13][values][0]=1636405200&leads[update][0][custom_fields][14][id]=670612&leads[update][0][custom_fields][14][name]=REFERER&leads[update][0][custom_fields][14][values][0][value]=https://mylogoped.online/reading?utm_source=blogger&utm_campaign=daria_moguchaya&utm_medium=rg#rec319161715&leads[update][0][custom_fields][15][id]=680880&leads[update][0][custom_fields][15][name]=FORMNAME&leads[update][0][custom_fields][15][values][0][value]=форма&leads[update][0][custom_fields][15][code]=FORMNAME&leads[update][0][custom_fields][16][id]=671845&leads[update][0][custom_fields][16][name]=UTM_SOURCE&leads[update][0][custom_fields][16][values][0][value]=blogger&leads[update][0][custom_fields][17][id]=671847&leads[update][0][custom_fields][17][name]=UTM_MEDIUM&leads[update][0][custom_fields][17][values][0][value]=rg&leads[update][0][custom_fields][18][id]=671849&leads[update][0][custom_fields][18][name]=UTM_CAMPAIGN&leads[update][0][custom_fields][18][values][0][value]=daria_moguchaya&leads[update][0][custom_fields][19][id]=670608&leads[update][0][custom_fields][19][name]=TRANID&leads[update][0][custom_fields][19][values][0][value]=2225828:2655884701&leads[update][0][custom_fields][20][id]=670610&leads[update][0][custom_fields][20][name]=FORMID&leads[update][0][custom_fields][20][values][0][value]=form319161715&leads[update][0][created_at]=1636435650&leads[update][0][updated_at]=1637662097&account[subdomain]=mylogoped&account[id]=24809335&account[_links][self]=https://mylogoped.amocrm.ru";
var two = "leads[update][0][id]=30983426&leads[update][0][name]=Lead from: https://mylogoped.online/#rec367114784&leads[update][0][status_id]=24809344&leads[update][0][price]=0&leads[update][0][responsible_user_id]=7420479&leads[update][0][last_modified]=1637662184&leads[update][0][modified_user_id]=7420479&leads[update][0][created_user_id]=0&leads[update][0][date_create]=1637661669&leads[update][0][pipeline_id]=1635139&leads[update][0][tags][0][id]=451580&leads[update][0][tags][0][name]=tilda&leads[update][0][tags][1][id]=475269&leads[update][0][tags][1][name]=Партнерка&leads[update][0][tags][2][id]=476169&leads[update][0][tags][2][name]=онлайн-занятия&leads[update][0][tags][3][id]=483228&leads[update][0][tags][3][name]=Акция +2&leads[update][0][tags][4][id]=493262&leads[update][0][tags][4][name]=неделя в подарок&leads[update][0][account_id]=24809335&leads[update][0][custom_fields][0][id]=683303&leads[update][0][custom_fields][0][name]=utm_referrer&leads[update][0][custom_fields][0][code]=UTM_REFERRER&leads[update][0][custom_fields][1][id]=928932&leads[update][0][custom_fields][1][name]=Менеджер 1 линии&leads[update][0][custom_fields][1][values][0][value]=Крутова Яна&leads[update][0][custom_fields][1][values][0][enum]=4205136&leads[update][0][custom_fields][2][id]=681336&leads[update][0][custom_fields][2][name]=Онлайн Категории&leads[update][0][custom_fields][2][values][0][value]=Звукопроизношение&leads[update][0][custom_fields][2][values][0][enum]=4188232&leads[update][0][custom_fields][3][id]=670612&leads[update][0][custom_fields][3][name]=REFERER&leads[update][0][custom_fields][3][values][0][value]=https://mylogoped.online/#rec367114784&leads[update][0][custom_fields][4][id]=670608&leads[update][0][custom_fields][4][name]=TRANID&leads[update][0][custom_fields][4][values][0][value]=2225828:2723274121&leads[update][0][custom_fields][5][id]=670610&leads[update][0][custom_fields][5][name]=FORMID&leads[update][0][custom_fields][5][values][0][value]=form367114784&leads[update][0][created_at]=1637661669&leads[update][0][updated_at]=1637662184&account[subdomain]=mylogoped&account[id]=24809335&account[_links][self]=https://mylogoped.amocrm.ru";
Logger.log(form2Json(one));
}

Here is the form2Json script itself

 /**
 *
 * @file Parse data that could contain objects nested up to 5 levels deep.
 * It's able to deal with both rather complex data, but not fail to decode a URI as simple as id=213.
 * @author Elias Van Ootegem {@link https://stackoverflow.com/users/1230836/elias-van-ootegem}
 * @see https://stackoverflow.com/a/10881657/1393023
 */

/**
 *
 * @param {string} formString
 * @return {object}
 */
function form2Json(formString) {
  'use strict';
  let obj;
  let i;
  let pt;
  let keys;
  let j;
  let ev;
  if (typeof form2Json.br !== 'function') {
    form2Json.br = function(repl) {
      if (repl.indexOf(']') !== -1) {
        return repl.replace(/\](. ?)(,|$)/g, function($1, $2, $3) {
          return form2Json.br($2   '}'   $3);
        });
      }
      return repl;
    };
  }
  formString =
    '{"'  
    (formString.indexOf('%') !== -1
      ? decodeURIComponent(formString)
      : formString)  
    '"}';
  obj = formString
    .replace(/\=/g, '":"')
    .replace(/&/g, '","')
    .replace(/\[/g, '":{"');
  obj = JSON.parse(
    obj.replace(/\](. ?)(,|$)/g, function($1, $2, $3) {
      return form2Json.br($2   '}'   $3);
    })
  );
  pt = ('&'   formString)
    .replace(/(\[|\]|\=)/g, '"$1"')
    .replace(/\]" /g, ']')
    .replace(/&([^\[\=] ?)(\[|\=)/g, '"&["$1]$2');
  pt = (pt   '"').replace(/^"&/, '').split('&');
  for (i = 0; i < pt.length; i  ) {
    ev = obj;
    keys = pt[i].match(/(?!:(\["))([^"] ?)(?=("\]))/g);
    for (j = 0; j < keys.length; j  ) {
      if (!Object.prototype.hasOwnProperty.call(ev, keys[j])) {
        if (keys.length > j   1) {
          ev[keys[j]] = {};
        } else {
          ev[keys[j]] = pt[i].split('=')[1].replace(/"/g, '');
          break;
        }
      }
      ev = ev[keys[j]];
    }
  }
  return obj;
}

CodePudding user response:

The issue is in the form value

leads[update][0][custom_fields][14][values][0][value]

The following section of your string:

leads[update][0][custom_fields][14][values][0][value]=https://mylogoped.online/reading?utm_source=blogger

will become decoded to the following:

leads[update][0][custom_fields][14][values][0][value]=https://mylogoped.online/reading?utm_source=blogger

The incriminating value being the url:

https://mylogoped.online/reading?utm_source=blogger

form2Json attempts to create a JSON object out of the string using conventional replacement methods:

formString =
    '{"'  
    (formString.indexOf('%') !== -1
        ? decodeURIComponent(formString)
        : formString)  
    '"}';

obj = formString
    .replace(/\=/g, '":"')
    .replace(/&/g, '","')
    .replace(/\[/g, '":{"');

Where formString is the string you pass to it (in your case, one).

Due to the line .replace(/\=/g, '":"') the = signifying a URL parametergets converted to a ":", and so then in the string that is provided to JSON.parse() reads:

"leads": {
  "update": {
    "0": {
      "custom_fields": {
        "14": {
          "values": {
            "0": {
              "value": "https://mylogoped.online/reading?utm_source": "blogger"
            }
          }
        }
      }
    }
  }
}

Which is an invalid JSON string and throws the error

SyntaxError: Unexpected token : in JSON at position 5759

Fix:

You need to encode the = in the URL before putting it into form2Json in some way

Perhaps change all = characters in the raw input to a different character string (such as {{ EQUALS_SIGN }}) and then after calling form2Json(one) replace all instances of the {{ EQUALS_SIGN }} string for an = whenever it is to be displayed anywhere

  • Related