ローカルJSONファイルのロード
-
27-10-2019 - |
質問
ローカルJSONファイルをロードしようとしていますが、機能しません。これが私のJavaScriptコードです(jQueryを使用してください:
var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);
test.jsonファイル:
{"a" : "b", "c" : "d"}
何も表示されず、FireBugはデータが未定義であることを教えてくれます。 Firebugではわかります json.responseText
そして、それは良くて有効ですが、私が線をコピーするとき、それは奇妙です:
var data = eval("(" +json.responseText + ")");
FireBugのコンソールでは、機能し、データにアクセスできます。
誰かが解決策を持っていますか?
解決
$.getJSON
非同期なので、する必要があります。
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
他のヒント
同じ必要性がありました(Angularjsアプリをテストするため)。見つけた唯一の方法は、require.jsを使用することです。
var json = require('./data.json'); //(with path)
注:ファイルは一度ロードされ、さらに呼び出しがキャッシュを使用します。
nodejsを使用してファイルを読む詳細: http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs
require.js: http://requirejs.org/
ユーザーにローカルJSONファイル(ファイルシステムのどこでも)を選択させたい場合は、次のソリューションが機能します。
使用しています。FileReaderとjson.parser(およびjqueryなし)を使用します。
<html>
<body>
<form id="jsonFile" name="jsonFile" enctype="multipart/form-data" method="post">
<fieldset>
<h2>Json File</h2>
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</fieldset>
</form>
<script type="text/javascript">
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
alert("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText(e) {
let lines = e.target.result;
var newArr = JSON.parse(lines);
}
}
</script>
</body>
</html>
これがFileReaderの良いイントロです: http://www.html5rocks.com/en/tutorials/file/dndfiles/
よりモダンな方法で、あなたは今、 APIを取得します:
fetch("test.json")
.then(response => response.json())
.then(json => console.log(json));
すべての最新のブラウザはFetch APIをサポートしています。 (インターネットエクスプローラーはそうではありませんが、エッジはそうします!)
ソース:
迅速で汚れたものを探している場合は、HTMLドキュメントのヘッドにデータをロードしてください。
data.js
var DATA = {"a" : "b", "c" : "d"};
index.html
<html>
<head>
<script src="data.js" ></script>
<script src="main.js" ></script>
</head>
...
</html>
main.js
(function(){
console.log(DATA) // {"a" : "b", "c" : "d"}
})()
Ace.webgeeker.xyz
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true);
// Replace 'my_data' with the path to your file
xobj.onreadystatechange = function() {
if (xobj.readyState === 4 && xobj.status === "200") {
// Required use of an anonymous callback
// as .open() will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
});
}
ES6バージョン
const loadJSON = (callback) => {
let xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true);
// Replace 'my_data' with the path to your file
xobj.onreadystatechange = () => {
if (xobj.readyState === 4 && xobj.status === "200") {
// Required use of an anonymous callback
// as .open() will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
const init = () => {
loadJSON((response) => {
// Parse JSON string into object
let actual_JSON = JSON.parse(response);
});
}
元のポスターの実際のコードの問題を理解したり、対処したりせずに、この質問が何回回答されたのか信じられません。とはいえ、私は自分自身が初心者です(わずか2か月のコーディング)。私のコードは完全に機能しますが、変更をお気軽にお問い合わせください。 これが解決策です:
//include the 'async':false parameter or the object data won't get captured when loading
var json = $.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false});
//The next line of code will filter out all the unwanted data from the object.
json = JSON.parse(json.responseText);
//You can now access the json variable's object data like this json.a and json.c
document.write(json.a);
console.log(json);
上記で提供したのと同じコードを書くための短い方法は次のとおりです。
var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
$ .getjsonの代わりに$ .ajaxを使用して、コードをまったく同じ方法で記述することもできます。
var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
最後に、これを行う最後の方法 関数に$ .AJAXを包むことです。私はこれを信用することはできませんが、私はそれを少し修正しました。私はそれをテストしました、そしてそれは動作し、上記の私のコードと同じ結果を生成します。ここでこの解決策を見つけました - > JSONを変数にロードします
var json = function () {
var jsonTemp = null;
$.ajax({
'async': false,
'url': "http://spoonertuner.com/projects/test/test.json",
'success': function (data) {
jsonTemp = data;
}
});
return jsonTemp;
}();
document.write(json.a);
console.log(json);
test.json 上記のコードに表示されるファイルは、私のサーバーでホストされており、彼(元のポスター)が投稿したのと同じJSONデータオブジェクトが含まれています。
{
"a" : "b",
"c" : "d"
}
ES6からのインポートが言及されていないことに驚いています(小さなファイルで使用)
元: import test from './test.json'
Webpack 2 <uses the json-loader
デフォルトとして .json
ファイル。
https://webpack.js.org/guides/migrating/#json-loader-is-not-required-anymore
為に タイプスクリプト:
import test from 'json-loader!./test.json';
TS2307(TS)はモジュール 'JSON-Roader!./ Suburbs.json'を見つけることができません
それを機能させるには、最初にモジュールを宣言する必要がありました。これが誰かのために数時間節約することを願っています。
declare module "json-loader!*" {
let json: any;
export default json;
}
...
import test from 'json-loader!./test.json';
省略しようとした場合 loader
から json-loader
次のエラーがありました webpack
:
変化の破壊:ローダーを使用するときに「-loader」の接尾辞を省略することはできなくなりました。 「JSON」の代わりに「JSON-Roader」を指定する必要があります。 https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed
試してみてください(ただし、JavaScriptがクライアントファイルシステムにアクセスしていないことにも注意してください):
$.getJSON('test.json', function(data) {
console.log(data);
});
最近 D3JS ローカルJSONファイルを処理できます。
これが問題ですhttps://github.com/mbostock/d3/issues/673
これは、D3がローカルJSONファイルで動作するためのパッチインオーダーです。https://github.com/mbostock/d3/pull/632
(失敗して)ローカルJSONファイルをロードしようと試みたときにこのスレッドを見つけました。このソリューションは私のために働いた...
function load_json(src) {
var head = document.getElementsByTagName('head')[0];
//use class, as we can't reference by id
var element = head.getElementsByClassName("json")[0];
try {
element.parentNode.removeChild(element);
} catch (e) {
//
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
script.className = "json";
script.async = false;
head.appendChild(script);
//call the postload function after a slight delay to allow the json to load
window.setTimeout(postloadfunction, 100)
}
...そしてこのように使用されています...
load_json("test2.html.js")
...そしてこれがです <head>
...
<head>
<script type="text/javascript" src="test.html.js" class="json"></script>
</head>
TypeScriptでは、インポートを使用してローカルJSONファイルをロードできます。たとえば、font.jsonのロード:
import * as fontJson from '../../public/fonts/font_name.json';
これには、tsconfigフラグが必要です-resolvejsonmodule:
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
詳細については、TypeScriptのリリースノートを参照してください。 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html
Angular(またはその他のフレームワーク)では、HTTPを使用してロードできます。このようなものを使用できます。
this.http.get(<path_to_your_json_file))
.success((data) => console.log(data));
お役に立てれば。
$.ajax({
url: "Scripts/testingJSON.json",
//force to handle it as text
dataType: "text",
success: function (dataTest) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(dataTest);
//now json variable contains data in json format
//let's display a few items
$.each(json, function (i, jsonObjectList) {
for (var index = 0; index < jsonObjectList.listValue_.length;index++) {
alert(jsonObjectList.listKey_[index][0] + " -- " + jsonObjectList.listValue_[index].description_);
}
});
}
});
JSONのローカル配列を使用している場合 - 質問であなたのexmapleで示したように(test.json)、あなたは parseJSON
jQueryの方法 - >
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
getJSON
リモートサイトからJSONを取得するために使用されます - ローカルで動作しません(ローカルHTTPサーバーを使用していない限り)
Googleの閉鎖ライブラリを使用したソリューションは見つかりませんでした。したがって、将来の眺めのリストを完成させるために、閉鎖ライブラリを使用してローカルファイルからJSONをロードする方法を次に示します。
goog.net.XhrIo.send('../appData.json', function(evt) {
var xhr = evt.target;
var obj = xhr.getResponseJson(); //JSON parsed as Javascript object
console.log(obj);
});
私が使用したいアプローチは、JSONをリテラルでJSONにパッド/ラップし、.JSONPファイル拡張子でファイルを保存することです。また、このメソッドは、代わりに新しいJSONPファイル(test.jsonp)で作業するため、元のJSONファイル(TEST.JSON)を変更しません。ラッパーの名前は何でもかまいませんが、JSONPを処理するために使用するコールバック関数と同じ名前である必要があります。 stest.jsonを使用して、「test.jsonp」ファイルのJSONPラッパーの追加を示す例として投稿します。
json_callback({"a" : "b", "c" : "d"});
次に、スクリプトにグローバルスコープを備えた再利用可能な変数を作成して、返されたJSONを保持します。これにより、返されたJSONデータが、コールバック関数のみではなく、スクリプト内の他のすべての機能で利用可能になります。
var myJSON;
次に、スクリプトインジェクションによってJSONを取得するための単純な機能があります。 IEはjQuery .appendメソッドをサポートしていないため、ここではjqueryを使用してスクリプトをドキュメントヘッドに追加することはできません。以下のコードでコメントしたjQueryメソッドは、.appendメソッドをサポートする他のブラウザで動作します。違いを示すための参照として含まれています。
function getLocalJSON(json_url){
var json_script = document.createElement('script');
json_script.type = 'text/javascript';
json_script.src = json_url;
json_script.id = 'json_script';
document.getElementsByTagName('head')[0].appendChild(json_script);
// $('head')[0].append(json_script); DOES NOT WORK in IE (.append method not supported)
}
次は、JSON結果データをグローバル変数に取得するための短く単純なコールバック関数(JSONPラッパーと同じ名前)です。
function json_callback(response){
myJSON = response; // Clone response JSON to myJSON object
$('#json_script').remove(); // Remove json_script from the document
}
JSONデータは、DOT表記を使用してスクリプトの任意の関数によってアクセスできるようになりました。例として:
console.log(myJSON.a); // Outputs 'b' to console
console.log(myJSON.c); // Outputs 'd' to console
この方法は、あなたが見ているものとは少し異なるかもしれませんが、多くの利点があります。まず、同じJSONPファイルをローカルで、または同じ機能を使用してサーバーからロードできます。ボーナスとして、JSONPはすでにクロスドメインに優しい形式であり、RESTタイプAPIで簡単に使用できます。
確かに、エラー処理機能はありませんが、なぜ必要なのか?この方法を使用してJSONデータを取得できない場合は、JSON自体にいくつかの問題があることをほぼ賭けて、Good JSON Balidatorで確認します。
JSONをJavaScriptファイルに入れることができます。これは、jQueryの使用を使用して(クロムでも)ローカルにロードできます getScript()
関数。
MAP-01.jsファイル:
var json = '{"layers":6, "worldWidth":500, "worldHeight":400}'
main.js
$.getScript('map-01.js')
.done(function (script, textStatus) {
var map = JSON.parse(json); //json is declared in the js file
console.log("world width: " + map.worldWidth);
drawMap(map);
})
.fail(function (jqxhr, settings, exception) {
console.log("error loading map: " + exception);
});
出力:
world width: 500
JSON変数がJSファイルに宣言され、割り当てられていることに注意してください。
json_str = String.raw`[{"name": "Jeeva"}, {"name": "Kumar"}]`;
obj = JSON.parse(json_str);
console.log(obj[0]["name"]);
JSON用の新しいJavaScriptファイルを作成し、JSONデータを貼り付けたように、Cordovaアプリのためにこれを行いました。 String.raw
次に、それを解析します JSON.parse
function readTextFile(srcfile) {
try { //this is for IE
var fso = new ActiveXObject("Scripting.FileSystemObject");;
if (fso.FileExists(srcfile)) {
var fileReader = fso.OpenTextFile(srcfile, 1);
var line = fileReader.ReadLine();
var jsonOutput = JSON.parse(line);
}
} catch (e) {
}
}
readTextFile("C:\\Users\\someuser\\json.txt");
まず第一に、ネットワークタブから、サービスのネットワークトラフィックを記録し、応答本体から、ローカルファイルにJSONオブジェクトをコピーして保存しました。次に、ローカルファイル名で関数を呼び出します。上記のJSONOUTOUTでJSONオブジェクトを表示できるはずです。
私のために働いたのは次のとおりです。
入力:
http://ip_address//some_folder_name//render_output.html?relative/path/to/json/fie.json
JavaScriptコード:
<html>
<head>
<style>
pre {}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>
<script>
function output(inp) {
document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}
function gethtmlcontents(){
path = window.location.search.substr(1)
var rawFile = new XMLHttpRequest();
var my_file = rawFile.open("GET", path, true) // Synchronous File Read
//alert('Starting to read text')
rawFile.onreadystatechange = function ()
{
//alert("I am here");
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
//alert(allText)
var json_format = JSON.stringify(JSON.parse(allText), null, 8)
//output(json_format)
output(syntaxHighlight(json_format));
}
}
}
rawFile.send(null);
}
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
gethtmlcontents();
</script>
</head>
<body>
</body>
</html>
私がしたことは、JSONファイルを少し編集することでした。
myfile.json
=> myfile.js
JSONファイルで、(JS変数にしてください)
{name: "Whatever"}
=> var x = {name: "Whatever"}
最後に、
export default x;
それで、
import JsonObj from './myfile.js';
Pythonがローカルマシンにインストールされている場合(またはインストールを気にしないでください)、以下に使用しているローカルJSONファイルアクセス問題のブラウザに依存しない回避策を紹介します。
JavaScriptオブジェクトとしてデータを返す関数を作成することにより、JSONファイルをJavaScriptに変換します。その後、ロードできますu003Cscript> tag and call the function to get the data you want.
の登場 Pythonコード
import json
def json2js(jsonfilepath, functionname='getData'):
"""function converting json file to javascript file: json_data -> json_data.js
:param jsonfilepath: path to json file
:param functionname: name of javascript function which will return the data
:return None
"""
# load json data
with open(jsonfilepath,'r') as jsonfile:
data = json.load(jsonfile)
# write transformed javascript file
with open(jsonfilepath+'.js', 'w') as jsfile:
jsfile.write('function '+functionname+'(){return ')
jsfile.write(json.dumps(data))
jsfile.write(';}')
if __name__ == '__main__':
from sys import argv
l = len(argv)
if l == 2:
json2js(argv[1])
elif l == 3:
json2js(argv[1], argv[2])
else:
raise ValueError('Usage: python pathTo/json2js.py jsonfilepath [jsfunctionname]')