javascript - 使用 javascript 将 JSON 数组转换为单独的变量

标签 javascript php json

我有以下从 API 输出的 JSON 数组。

{
    "location": {
        "name": "Alanallur",
        "region": "Kerala",
        "country": "India",
        "lat": 11.01,
        "lon": 76.33,
        "tz_id": "Asia/Kolkata",
        "localtime_epoch": 1470998311,
        "localtime": "2016-08-12 10:38"
    },
    "current": {
        "last_updated_epoch": 1470997826,
        "last_updated": "2016-08-12 10:30",
        "temp_c": 28.0,
        "temp_f": 82.4,
        "is_day": 1,
        "condition": {
            "text": "Moderate rain",
            "icon": "//cdn.apixu.com/weather/64x64/day/302.png",
            "code": 1189
        },
        "wind_mph": 8.1,
        "wind_kph": 13.0,
        "wind_degree": 340,
        "wind_dir": "NNW",
        "pressure_mb": 1013.0,
        "pressure_in": 30.4,
        "precip_mm": 0.0,
        "precip_in": 0.0,
        "humidity": 79,
        "cloud": 0,
        "feelslike_c": 32.2,
        "feelslike_f": 89.9
    }
}

我想使用 JavaScript 将此数组拆分为单独的变量

最佳答案

Json代码

{
posts:[
   "location": {
        "name": "Alanallur",
        "region": "Kerala",
        "country": "India",
        "lat": 11.01,
        "lon": 76.33,
        "tz_id": "Asia/Kolkata",
        "localtime_epoch": 1470998311,
        "localtime": "2016-08-12 10:38"
    },
    "current": {
        "last_updated_epoch": 1470997826,
        "last_updated": "2016-08-12 10:30",
        "temp_c": 28.0,
        "temp_f": 82.4,
        "is_day": 1,
        "condition": {
            "text": "Moderate rain",
            "icon": "//cdn.apixu.com/weather/64x64/day/302.png",
            "code": 1189
        },
        "wind_mph": 8.1,
        "wind_kph": 13.0,
        "wind_degree": 340,
        "wind_dir": "NNW",
        "pressure_mb": 1013.0,
        "pressure_in": 30.4,
        "precip_mm": 0.0,
        "precip_in": 0.0,
        "humidity": 79,
        "cloud": 0,
        "feelslike_c": 32.2,
        "feelslike_f": 89.9
    }
}

在 JavaScript 中使用

 json.parse()

PHP 代码

<?php
// copy file content into a string var
$json_file = file_get_contents('posts.json');
// convert the string to a json object
$jfo = json_decode($json_file);
// read the title value
$title = $jfo->result->title;
// copy the posts array to a php var
$posts = $jfo->result->posts;
// listing posts
foreach ($posts as $post) {
    echo $post->title;
}
?>

希望这有帮助。 :)

关于javascript - 使用 javascript 将 JSON 数组转换为单独的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38911057/

相关文章:

javascript - 将数据从父窗口传递到子窗口

php - 在 xampp 等本地服务器上设置和测试 facebook 连接

java - java和php中的时间戳有什么区别?

c# - RestSharp 和 OData - 反序列化 JSON 的问题

javascript - 检查 json Javascript/Jquery 中是否存在数组

javascript - 将数组传递给函数,如何?

Javascript 在 Chrome 中返回 null,在源代码中返回 HTML 元素

javascript - 访问 Nuxt 组件中的 axios 返回数组以便循环

javascript - 覆盖 Foundation 4 Joyride 的默认设置

php - 将当前年份和月份与 sql 查询中输入的数据库年月进行比较