Json_decode给我一个字符串,如何从中提取值?

时间:2018-09-12 21:13:59

标签: php

我无法从JSON解码字符串中获取值

这是我尝试过的

$data = json_decode(stripslashes($_POST['data']),true);
$data = TYPE --> String

给我:

 "[{"name":"option_page","value":"gpinator_plugin_options"}, 
  {"name":"action","value":"update"}, 
  {"name":"_wpnonce","value":"b0b29d4682"}, 
  {"name":"_wp_http_referer","value":"/wordpress/wordpress-4.9.1/wordpress/wp-admin/admin.php?page=gpinator_settings_admin_page"}, 
  {"name":"gpinator_category_allowed","value":"on"}, 
  {"name":"gpinator_languages_swedish","value":"on"}]"

$ _ POST ['data']给我

"\"{\\\"name\\\":\\\"option_page\\\",\\\"value\\\":\\\"gpinator_plugin_options\\\"} 
   ,{\\\"name\\\":\\\"action\\\",\\\"value\\\":\\\"update\\\"}, 
    {\\\"name\\\":\\\"_wpnonce\\\",\\\"value\\\":\\\"b0b29d4682\\\"}, {\\\"name\\\":\\\"_wp_http_referer\\\",\\\"value\\\":\\\"/wordpress/wordpress- 
  4.9.1/wordpress/wp-admin/admin.php?page=gpinator_settings_admin_page\\\"},       
{\\\"name\\\":\\\"gpinator_category_allowed\\\",\\\"value\\\":\\\"on\\\"},{\\\"name\\\":\\\"gpinator_languages_swedish\\\",\\\"value\\\":\\\"on\\\"}]\""

没有,我尝试了所有方式来提取数据。

如果我这样做

  $obj = $data[0];

我只会得到

      "["

我运行这些功能

$josnerr = json_last_error();  result --> 0
$josnerree = json_last_error_msg(); result "No error"

执行print_r($ data);

它给了我

 [{"name":"option_page","value":"gpinator_plugin_options"}, 
 {"name":"action","value":"update"}, 
 {"name":"_wpnonce","value":"b0b29d4682"}, 
 {"name":"_wp_http_referer","value":"/wordpress/wordpress-4.9.1/wordpress/wp-admin/admin.php?page=gpinator_settings_admin_page"}, 
 {"name":"gpinator_category_allowed","value":"on"}, 
 {"name":"gpinator_languages_swedish","value":"on"}]

如何访问我的数据?

1 个答案:

答案 0 :(得分:0)

我认为您的json对象是对象的字符串表示形式。就像您两次json_encode结构一样,您首先获得json_string,然后获得该字符串的json编码字符串。示例:假设您将其传递给json_decode:

var_dump(json_decode('[{"a": "b"}, {"b": "a"}]', true)) 
// ==> 
array(2) {
  [0] =>
  array(1) {
    'a' =>
    string(1) "b"
  }
  [1] =>
  array(1) {
    'b' =>
    string(1) "a"
  }
}

虽然有这样小的变化:

var_dump(json_decode('"[{\"a\": \"b\"}, {\"b\": \"a\"}]"', true)) 
// ==> 
string(24) "[{"a": "b"}, {"b": "a"}]"

也许您应该先查看数据,然后再将其传递给json_decode?无论如何,问题出在客户端。

更新

查看您提供的帖子数据确实是我的想象。您需要在客户端修复此问题。如果您别无选择,只能将其修复,则可以对值进行双解码:

$strJson = json_decode('"[{\"a\": \"b\"}, {\"b\": \"a\"}]"');
$arrPayload = json_decode($strJson, true);
var_dump($arrPayload); 
// ==> 
array(2) {
  [0] =>
  array(1) {
    'a' =>
    string(1) "b"
  }
  [1] =>
  array(1) {
    'b' =>
    string(1) "a"
  }
}