Rinko128
Rinko128

Reputation: 3

Javascript: how to read a value from a json file?

I am a beginner in Javascript. I hope to get some help.

I built a local server using MAMP, and all my files are local. I want to read a value from a json file. This json file(data.json) has only one item {"type":2}, and I only want to use the value(2 in this case). But the value of "type" changes, so Javascript should read it constantly and maybe save it into a var in Javascript.

Can I listen for changes to that file so that I can be sure I always have the most up to date value for type?

I am still not familiar with Javascript. I would really appreciate it if you could give me some specific codes or examples.

Upvotes: 0

Views: 3730

Answers (2)

user1037355
user1037355

Reputation:

JSON can come from anywhere, inbuilt into jquery is parseJSON which will return the json input string as a javascript object.

http://api.jquery.com/jquery.parsejson/

var obj = $.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

where the json can come from anywhere.. an ajax call or where ever else.

$.ajax({
  url:'some url',
  data: someobject,
  type: 'get',
  success: function( responseFromServer ){
     var obj = $.parseJSON( responseFromServer  );
     alert( obj.name === "John" );
  }
});

Upvotes: 0

RobertoNovelo
RobertoNovelo

Reputation: 3809

//Either

var json = {test:"test"};

console.log(json);

//Access JSON

console.log(json.test);

//Or

$.getJSON( "test.json", function( data ) {
  
  //Assign the json to your JSON variable
  json = data;
  
});

console.log(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions