簡體   English   中英

如何使用php / jquery將此格式錯誤的字符串轉換為json

[英]how to convert this malformed string to json with php/jquery

我有這個字符串-

{

          'Carlos':

           {
             Name: 'Spers',
             href: "http://google.com"
           }, 
          'Winter':

           {
             Name: 'Warres',
             href: "http://yahoo.com"
           }, 
          'Doer':

           {
             Name: 'Pinto',
             href: "http://carpet.com"
           } 
}

我用JSLinter驗證了,它說無效並有多個錯誤。 我明白這一點。 問題是,這就是我從第三方服務獲得的。 我必須離開它。 現在,我堅持將其轉換為JSON對象以使用它。

當我在PHP中使用json_decode($thisStirng)時,它返回null。 $.parseJSON(data)返回我錯誤。

我想以某種樣式顯示網頁上的數據。 所以最后,我希望在客戶端使用json對象。 因此,無論如何都可以使用PHP或jQuery將數據轉換為JSON。

我應該怎么做?

更新資料

我得到了一個與json_decode($thisStirng, true)關聯的數組。 現在,我想將其作為字符串echo ,以便在瀏覽器上可以使用數組索引訪問它。

謝謝大家-讓它按以下方式工作-

 $someObject = json_decode($thisStirng,true);

 $myarry = array();

 foreach ($someObject as $key => $val) {
    $temparray = array();
    $temparray[]= $key;
    $temparray[]= $val;
    $myarry[]= $temparray;
}

 echo json_encode($myarry);

現在,在jQuery中,我可以訪問data[index][0]作為“ Carlos”和其他動態鍵。 data[index][1]是具有“名稱”和“ href”屬性的對象。

您可以嘗試此代碼。

 $jsonData='{
      "Carlos":
       {
         "Name": "Spers",
         "href": "http://google.com"
       }, 
      "Winter":

       {
         "Name": "Warres",
         "href": "http://yahoo.com"
       }, 
      "Doer":
       {
         "Name": "Pinto",
         "href": "http://carpet.com"
       } 
}';

$arr1=array();
$arr2=array();
$arr3=array();
$phpArray = json_decode($jsonData, true);
foreach ($phpArray as $key => $value) { 

    $arr1=array();
    $arr1[]=$key;

    foreach ($value as $k => $v) { 
        $arr2=array();

        $arr2[$k]=$v;
        $arr3[]=$arr2;
    }
}
echo $arr3[0]['Name'];

嘗試使用此:

<?php
$jsonData='{
      "Carlos":
       {
         "Name": "Spers",
         "href": "http://google.com"
       }, 
      "Winter":

       {
         "Name": "Warres",
         "href": "http://yahoo.com"
       }, 
      "Doer":
       {
         "Name": "Pinto",
         "href": "http://carpet.com"
       } 
}';
$phpArray = json_decode($jsonData, true);


foreach ($phpArray as $key => $value) {
    echo "Key:".$key. ", Name:". $value['Name'].'<br>';

}

?>

輸出:

Key:Carlos, Name:Spers
Key:Winter, Name:Warres
Key:Doer, Name:Pinto

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM