【问题标题】:Php convert string into JSON or an Arrayphp 将字符串转换为 JSON 或数组
【发布时间】:2016-03-08 15:11:00
【问题描述】:

谁能帮我把字符串转换成数组或JSON?请看下面的文本示例;

{
    "account_id": "dfdfdf",
    "email": "mail-noreply@google.com",
    "id": "dfdfdf",
    "name": "Gmail Team",
    "object": "contact",
    "phone_numbers": []
},
{
    "account_id": "dfdf",
    "email": "saaddfsdfsdsfsdf@gmail.com",
    "id": "dfdf",
    "name": "Ab",
    "object": "contact",
    "phone_numbers": []
},
{
    "account_id": "dfdf",
    "email": "abc@gmail.com",
    "id": "dfdfdf",
    "name": "xyz",
    "object": "contact",
    "phone_numbers": []
},

我试过了

preg_match_all("/\{([^\)]*)\},/", $stream[0], $aMatches);

但它不返回任何东西。我也尝试过 json_decode、json_encode 但找不到任何成功。

谢谢

【问题讨论】:

  • @fusion3k 已经试过了。这是字符串,结果为 null
  • 请提供 real 字符串的链接。以您的示例为例,以下提供的答案很好。
  • 感谢@fusion3k 的支持。我同意,如果问题仍然存在,给出的字符串与他看到的不同。

标签: php arrays json


【解决方案1】:

目标是将其转换为适当的 JSON 格式,以便您可以使用json_decode。我将按步骤分解:

  1. 删除所有\n 字符:

    $string = str_replace('\n', '', $string);
    
  2. 去掉最后一个逗号

    $string = rtrim($string, ',');
    
  3. 添加括号

    $string = "[" . trim($string) . "]";
    
  4. 把它变成PHP数组:

    $json = json_decode($string, true);
    

结果:

$string = ''; //your string
$string = str_replace('\n', '', $string);
$string = rtrim($string, ',');
$string = "[" . trim($string) . "]";
$json = json_decode($string, true);
var_dump($json);

输出:

array (size=3)
  0 => 
    array (size=6)
      'account_id' => string '43z95ujithllc32fn02u8ynef' (length=25)
      'email' => string 'mail-noreply@google.com' (length=23)
      'id' => string '955xl0q3h9qe0sc11so8cojo2' (length=25)
      'name' => string 'Gmail Team' (length=10)
      'object' => string 'contact' (length=7)
      'phone_numbers' => 
        array (size=0)
          empty
  1 => 
    array (size=6)
      'account_id' => string '43z95ujithllc32fn02u8ynef' (length=25)
      'email' => string 'test-email1@gmail.com' (length=21)
      'id' => string '3u4e6i9ka3e7ad4km90nip73u' (length=25)
      'name' => string 'Test Account 1' (length=14)
      'object' => string 'contact' (length=7)
      'phone_numbers' => 
        array (size=0)
          empty
  2 => 
    array (size=6)
      'account_id' => string '43z95ujithllc32fn02u8ynef' (length=25)
      'email' => string 'test-email@gmail.com' (length=20)
      'id' => string 'bt3lphmp0g14y82zelpcf0w0r' (length=25)
      'name' => string 'Test Account' (length=12)
      'object' => string 'contact' (length=7)
      'phone_numbers' => 
        array (size=0)
          empty

【讨论】:

  • 那么您没有在原始帖子中提供所有字符串。
  • 你的字符串是如何形成的?你从哪里得到字符串?
  • 这是来自第三方 API Nylas 的字符串响应。我发布的正是我所拥有的。我想要数组,其中{}, 之间的数据可以作为内部数组获取
  • 我看到您更新了您的字符串,但这与您的原始字符串有很大不同。在您拥有\n 个字符之前……他们发生了什么事?
  • 在这种情况下,按照我的回答做,但不要按照步骤 1。
猜你喜欢
  • 1970-01-01
  • 2016-04-28
  • 1970-01-01
  • 2016-06-03
  • 2014-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多