user1544358
user1544358

Reputation: 67

Simple JSON file produces Undefined error Javascript

I have a simple set of HTML and JS files that both spectacularly fail, and I can't figure out why:

<html>
 <head>
  <script type="text/javascript" src="data.json"></script>
 </head>
 <body>
 </body>
</html>
var data = '{"name" : "Phil Powell"}';
alert(data + ' ' + data.name + ' ' + data.type);

But every single time I try to open this up, I get the exact same error every single time:

{"name" : "Phil Powell"} undefined undefined

What am I doing wrong? All I want to do is parse an external JSON file, and I can't seem to do it.

Please help.

Thanks

Upvotes: 1

Views: 240

Answers (6)

sonEtLumiere
sonEtLumiere

Reputation: 4562

did you try src= data.js ??

<script type="text/javascript" src="data.js"></script>

Upvotes: 1

Girish Sasidharan
Girish Sasidharan

Reputation: 588

In two ways you can make it work,

1. Removing single quotes from the string

var data = '{"name" : "Phil Powell","type":"something"}';

instead of this use below

var data = {"name" : "Phil Powell","type":"something"};

console.log(data.name, data.type);

2. Convert your string to JSON object using JSON.parse()

`var data = '{"name" : "Phil Powell","type":"something"}';`

`var obj = JSON.parse(data);`

`console.log(data.name, data.type);`

Upvotes: 1

sonEtLumiere
sonEtLumiere

Reputation: 4562

I hope this helps

var data = {"name" : "Phil Powell", "type" : "Mars Volta"};
console.log(data['name'] + ' ' + data['type']);

var data = '{"name" : "Phil Powell", "type" : "Mars Volta"}';
var obj = JSON.parse(data);
console.log(obj.name + ' ' + obj.type);

Upvotes: 1

Harpreet Singh
Harpreet Singh

Reputation: 979

Remove object quotes like :

var data = {"name" : "Phil Powell", "type" : "ABC"};
alert(data.name + ' ' + data.type);

Upvotes: 1

Robert Ravikumar
Robert Ravikumar

Reputation: 922

var data = '{"name" : "Phil Powell"}';

remove the enclosing apostrophe lie shown below

var data = {"name" : "Phil Powell"};

Upvotes: 2

HW Siew
HW Siew

Reputation: 1003

You data is a string. You need to first convert data to object to access by key.

var data = '{"name" : "Phil Powell","type":"something"}';
var obj = JSON.parse(data);

console.log(data + ' ' + obj.name + ' ' + obj.type);

Upvotes: 1

Related Questions