简体   繁体   English

Javascript:如何从json文件读取值?

[英]Javascript: how to read a value from a json file?

I am a beginner in Javascript. 我是Java语言的初学者。 I hope to get some help. 我希望能得到一些帮助。

I built a local server using MAMP, and all my files are local. 我使用MAMP构建了本地服务器,并且我所有的文件都是本地的。 I want to read a value from a json file. 我想从json文件中读取一个值。 This json file(data.json) has only one item {"type":2} , and I only want to use the value(2 in this case). 这个json文件(data.json)只有一项{"type":2} ,我只想使用value(在这种情况下为2)。 But the value of "type" changes, so Javascript should read it constantly and maybe save it into a var in Javascript. 但是“类型”的值发生了变化,因此Javascript应该不断读取它,并可能将其保存到Java语言中的var中。

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. 我仍然不熟悉Javascript。 I would really appreciate it if you could give me some specific codes or examples. 如果您能给我一些特定的代码或示例,我将不胜感激。

 //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> 

JSON can come from anywhere, inbuilt into jquery is parseJSON which will return the json input string as a javascript object. JSON可以来自任何地方,内置在jquery中的是parseJSON,它将以javascript对象的形式返回json输入字符串。

http://api.jquery.com/jquery.parsejson/ 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. json可以来自任何地方.. ajax调用或其他任何地方。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM