将方括号中的多个字符串的文本解析为数组

时间:2018-11-21 20:54:07

标签: javascript jquery arrays json parsing

我在解析如下内容时遇到问题:

{form_settings['settings']['title']: "Titulek", form_settings['settings']['description']: "Popisek formuláře...", form_settings['settings']['gdpr']: "ip", form_settings['settings']['acquisition']: "n", form_settings['settings']['style_form']: "without_border", …}

我想要类似PHP的东西,您可以在其中调用

$form_settings['settings']['title']

但是您不能在javascript中做到这一点,我想在php中使用类似的数组,我想做类似的事情

form_settings['settings']['title']

因为它不起作用,您知道如何解析它吗?感谢您的回答!

//编辑

<div class="col-md-10 col-form-label">
  <input type="text" id="title-for-receiver" class="form-control" name="form_settings['email']['{$input_form['EMAIL']['title_for_receiver']->name}']" value={$input_form['EMAIL']['title_for_receiver']->value} />
</div>

我通过javascript得到了这些值

function getFormData(form){
var unindexed_array = form.serializeArray();
var indexed_array = {};

$.map(unindexed_array, function(n, i){
    indexed_array[n['name']] = n['value'];
});

return indexed_array;
}

1 个答案:

答案 0 :(得分:1)

这不是您可以解析的内容。 “ parse”表示字符串或可以的东西。此:无法“解析”:

  1. 它具有单引号'和双引号",因此NEITHER会努力使其成为可解析对象的字符串。
  2. 它具有不带引号的内部元素
  

{form_settings ['settings'] ['title']:“ Titulek”,   form_settings ['settings'] ['description']:“ Popisekformuláře...”,   form_settings ['settings'] ['gdpr']:“ ip”,   form_settings ['settings'] ['acquisition']:“ n”,   form_settings ['settings'] ['style_form']:“无边框”,...}

编辑:我添加了mythingString,其解析显然更加明显。

也许传递一个更好的对象:

var mything = {
  "form_settings['settings']['title']": "Titulek",
  "form_settings['settings']['description']": "Popisek formuláře...",
  "form_settings['settings']['gdpr']": "ip",
  "form_settings['settings']['acquisition']": "n",
  "form_settings['settings']['style_form']": "without_border"
};

console.log(mything["form_settings['settings']['title']"]);

var mything2 = {
  form_settings: {
    settings: {
      'title': "Titulek",
      'description': "Popisek formuláře...",
      'gdpr': "ip",
      'acquisition': "n",
      'style_form': "without_border"
    }
  }
};
console.log(mything2.form_settings['settings']['title']);
console.log(mything2.form_settings.settings.title);

var mythingString = '{"form_settings[settings][title]": "Titulek",  "form_settings[settings][description]": "Popisek formuláře...", "form_settings[settings][gdpr]": "ip",  "form_settings[settings][acquisition]": "n", "form_settings[settings][style_form]": "without_border"}';

var parsedThing = JSON.parse(mythingString);
console.log(parsedThing["form_settings[settings][title]"]);