使用PHP打印Json字符串

时间:2016-08-08 07:24:18

标签: php json

Json String

我需要迭代String并打印整个数据。

打印时我得到非法胶印。##

$string = '{  
       "ConditionArray":[  
          {  
             "condition_image":"\/storage\/emulated\/0\/androidlav\/470-twitter.jpg (image\/jpg)",
             "condition_name":"Maleria",
             "profile_id":"49"
          },
          {  
             "condition_image":"\/storage\/emulated\/0\/androidlav\/470-twitter.jpg (image\/jpg)",
             "condition_name":"Maleria",
             "profile_id":"49"
          }
       ],

    "AllergiesArray":[  
          {  
             "condition_image":"\/storage\/emulated\/0\/androidlav\/470-twitter.jpg (image\/jpg)",
             "condition_name":"exapample",
             "profile_id":"50"
          },

       ]
    }';

2 个答案:

答案 0 :(得分:1)

你在AllergiesArray数组的最后一行中只有额外的逗号

 "AllergiesArray":[  
          {  
             "condition_image":"\/storage\/emulated\/0\/androidlav\/470-twitter.jpg (image\/jpg)",
             "condition_name":"exapample",
             "profile_id":"50"
          }, <--- remove this comma
    ]

$json =  (array)json_decode($string);  //convert array
print $json['ConditionArray'][0]->condition_image; 

答案 1 :(得分:0)

我发现你的错误json字符串没有正确编码

Invaild json对象

$string = '{
    "ConditionArray": [{
        "condition_image": "\/storage\/emulated\/0\/androidlav\/470-twitter.jpg (image\/jpg)",
        "condition_name": "Maleria",
        "profile_id": "49"
    }, {
        "condition_image": "\/storage\/emulated\/0\/androidlav\/470-twitter.jpg (image\/jpg)",
        "condition_name": "Maleria",
        "profile_id": "49"
    }],

    "AllergiesArray": [{
        "condition_image": "\/storage\/emulated\/0\/androidlav\/470-twitter.jpg (image\/jpg)",
        "condition_name": "exapample",
        "profile_id": "50"
    }, // => this line contain the error it has extra comma 
  ]
}';

使用http://jsonlint.com/验证json

有效的json对象

$string = '{
    "ConditionArray": [{
        "condition_image": "\/storage\/emulated\/0\/androidlav\/470-twitter.jpg (image\/jpg)",
        "condition_name": "Maleria",
        "profile_id": "49"
    }, {
        "condition_image": "\/storage\/emulated\/0\/androidlav\/470-twitter.jpg (image\/jpg)",
        "condition_name": "Maleria",
        "profile_id": "49"
    }],

    "AllergiesArray": [{
        "condition_image": "\/storage\/emulated\/0\/androidlav\/470-twitter.jpg (image\/jpg)",
        "condition_name": "exapample",
        "profile_id": "50"
    }
  ]
}';

var_dump(json_decode($string));