如何在json文件中插入新字段

时间:2018-01-19 05:57:10

标签: php json

我有一个像这样的JSON文件,

parent

我需要为它添加一个新字段并使用php获得这样的结果。任何帮助将不胜感激。

{
    "AAL": {
        "id": "32313",
        "airport_name": "Aalborg",
        "latitude": "57.1",
        "longitude": "9.85",
        "timezone": "2",
        "dst_indicator": "E",
        "city": "Aalborg",
        "country": "Denmark",
        "country_code": "DK",
        "region": "TC1",
        "listing_display": "true",
        "pseudonyms": ""
    },
    "AAR": {
        "id": "32314",
        "airport_name": "Tirstrup",
        "latitude": "56.15",
        "longitude": "10.2167",
        "timezone": "2",
        "dst_indicator": "E",
        "city": "Aarhus",
        "country": "Denmark",
        "country_code": "DK",
        "region": "TC1",
        "listing_display": "true",
        "pseudonyms": ""
    }
}

3 个答案:

答案 0 :(得分:1)

你可以通过这种方式实现输出..

$data= '{
    "AAL": {
        "id": "32313",
        "airport_name": "Aalborg",
        "latitude": "57.1",
        "longitude": "9.85",
        "timezone": "2",
        "dst_indicator": "E",
        "city": "Aalborg",
        "country": "Denmark",
        "country_code": "DK",
        "region": "TC1",
        "listing_display": "true",
        "pseudonyms": ""
    },
    "AAR": {
        "id": "32314",
        "airport_name": "Tirstrup",
        "latitude": "56.15",
        "longitude": "10.2167",
        "timezone": "2",
        "dst_indicator": "E",
        "city": "Aarhus",
        "country": "Denmark",
        "country_code": "DK",
        "region": "TC1",
        "listing_display": "true",
        "pseudonyms": ""
    }
}';

$arrData  =  json_decode($data,true);
foreach($arrData as $key=>$val){
    $arrData[$key]['station_code']=$key;
}

echo json_encode($arrData);
exit;

答案 1 :(得分:0)

你应该将json解析为php变量。在这里添加额外的字段并将其解析回json。

Check out the php documentation

答案 2 :(得分:0)

PHP中的JSON PARSING

要读取包含JSON数据的文件:

$json_array_assc = json_decode(file_get_contents($file_name), true);

要向数组添加字段,您可以执行以下操作:

$json_array_assc["NEWDATA"]=array('newdata1'=>'foo1','newdata2'=>'foo2');

要将新数据写入文件使用:

file_put_contents($file_name, json_encode($json_array_assc));

或者只是在控制台窗口上打印数组:

echo "<pre>";
print_r($json_array_assc);

OR

echo json_encode($json_array_assc);