0

I have the following JSON array that is output from an API.

{
    "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
    }
}

I want to split this array into separate variables using javascript

7
  • 1
    1) you have no array there, 2) JSON has no arrays, it is a string, 3) when parsed, you'll have a javascript object, with no array Commented Aug 12, 2016 at 6:10
  • You've no array in JSON String. json-parser.com/6d51ab22 Which field you want as separate variable ? Commented Aug 12, 2016 at 6:12
  • Should location and current be the two resulting variables? Commented Aug 12, 2016 at 6:12
  • You need to use JSON.parse(), it's explained here Commented Aug 12, 2016 at 6:13
  • Sorry ...I am a new b in javascript... Commented Aug 12, 2016 at 6:15

4 Answers 4

1

Json Code

{
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
    }
}

In javascript use

 json.parse()

PHP Code

<?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;
}
?>

Hope this helps. :)

Sign up to request clarification or add additional context in comments.

Comments

1

if this response is in data

check alert(typeof data) // it will show object or string

if it is not object then

data= JSON.parse(data)

now you can access it as saperate variable

if you want to access localtime of location then

alert(data.location.localtime)

I hope it make sense for you Check two example on jsfiddle

https://jsfiddle.net/5ov827oc/1/

https://jsfiddle.net/5ov827oc/2/

Comments

1

Try this code : Use developer console to view the output in browser

<script>
var str = '{"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,"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,"wind_degree":340,"wind_dir":"NNW","pressure_mb":1013,"pressure_in":30.4,"precip_mm":0,"precip_in":0,"humidity":79,"cloud":0,"feelslike_c":32.2,"feelslike_f":89.9}}';

if(typeof(str) == 'string'){
        str = JSON.parse(str);
        console.log(str.current)//return object
        console.log(str.location)//return object
        console.log(str.current.temp_c)//return string
        console.log(str.current.temp_f)//return string
        console.log(str.location.country)//return string
}
</script>

JSON.parse(str) is used to convert string to object

enter image description here

Comments

1

This is how you can get country and it's temparutre in separate JS variables.

var jsonobject=JSON.parse(json_string); // don't do this if you already have JSON Object instead of string.
var country=jsonobject.location.country. // Where location is another JSON Object
var temprature_c=jsonobject.current.temp_c; // current is another JSON Object
var temprature_f=jsonobject.current.temp_f; // current is another JSON Object

See this to debug your JSON. http://json-parser.com/6d51ab22

Where { } is a literal notation for an Object, access any property inside { } with . operator,
and [ ] is a literal notation for an Array. You can access array elements just like normal JS array using indices (e.g [0], [1] etc...)

4 Comments

"You keep using that word. I do not think it means what you think it means." There is no such thing as a "JSON Object".
{ } simply means it's an Object with key value pairs.
My original comment was a jest as a large number of people make that mistake hence the Princess Bride quote. However to clarify it a bit more: JSON is a String type and not an Object type. JSON is an acronym that means JavaScript Object Notation. In your answer you state "{ } means it's an JSON Object" which is patently false. It should read something like "{ } is literal notation for an Object" if you want to be accurate. Anyway, I hope this helps with understanding the difference.
@JasonCust Thanks for throwing the light, corrected my answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.