0

I'm having trouble on getting data from a local JSON file.

I have this peace of code

$.ajax({
    method: 'GET',
    url: './src/assets/api.json',
    success: (function(data) {
      $.each(data, function(index, val) {
        // Code
        console.log('Selling currency: ' + val.eur.pro);
      })
    }),
    error: function() {
      console.log('Something went wrong.');
    }
  })

That throws an error in console:

Cannot read property 'pro' of undefined

My JSON file looks like this

{
  "result": {
    "date": "23.08.2017",
    "eur": {
      "kup": "119.0352",
      "sre": "119.3934",
      "pro": "119.7516"
    },
    "usd": {
      "kup": "101.2032",
      "sre": "101.5077",
      "pro": "101.8122"
    },
    // other objects ...
  }
}

I don't know why is it throwing that error. If I were to remove the pro from the val.eur.pro and leave it like this val.eur it returns the object just fine. I don't know how am I suppose to access the 3rd value.

10
  • try to use $.each(data.result Commented Aug 25, 2017 at 10:37
  • parse your JSON response and then use it Commented Aug 25, 2017 at 10:38
  • 1
    if you console.log(data) what do you see? Commented Aug 25, 2017 at 10:39
  • Looping over a single object seems strange to me. What happens when you do console.log(val.eur)? Commented Aug 25, 2017 at 10:41
  • 2
    The code you've shown works fine: jsfiddle.net/qqfcdyns. This either means there's a discrepancy between your production code and what you've pasted above, or the response JSON is in a different format. Without any more information, we can't help you. Commented Aug 25, 2017 at 10:45

1 Answer 1

1

This might help you https://jsfiddle.net/rprxrhLp/

var data = {
  "result": {
    "date": "23.08.2017",
    "eur": {
      "kup": "119.0352",
      "sre": "119.3934",
      "pro": "119.7516"
    },
    "usd": {
      "kup": "101.2032",
      "sre": "101.5077",
      "pro": "101.8122"
    }
  }
};

var keys = Object.keys(data.result);
for(var key in keys){
  if( typeof data.result[keys[key]] === 'object'){
  	$.each(data.result[keys[key]], function(i, v){
    	console.log(keys[key] + ", " + i+ ": " + v)
    })
  	
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I worked with local data variable. Get the keys from result & then iterate over it.

For getting the pro value, just do this

var keys = Object.keys(data.result);
for(var key in keys){
   if( typeof data.result[keys[key]] === 'object'){
      console.log("Pro value:", data.result[keys[key]].pro);
   }
}

Hope this will help you.

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

Comments

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.