Load JSON file from local PC in Nativescript - javascript

So I am having trouble displaying the contents of my JSON file in nativescript using console commands.I basically want to display these contents and use the values in the file to do some additional functions.
This is the JS function that I have slightly rewritten from the NS documentation and Emil Oberg's solution on a different post
var fs = require('file-system');
var documents = fs.knownFolders.documents();
var jsonFile = documents.getFile('/Users/student/Desktop/Native_Script/Library/app/images/status.json');
var array;
var jsonData;
//console.log('Item:' +jsonFile);
jsonFile.readText()
.then(function (content)
{
try {
jsonData = JSON.parse(content);
//console.log('Item:' + JSON.stringify(jsonData));
array = new observableArrayModule.ObservableArray(jsonData);
}
catch (err) {
console.log(err);
}
console.log('Item:' +JSON.stringify(jsonData));
});
////////////////
JSON File:
[{
"Status": "3",
"Trend": "increase",
"Space": "Gleason"
}, {
"Status": "2",
"Trend": "decrease",
"Space": "PRR"
}, {
"Status": "4",
"Trend": "stable",
"Space": "WBR"
}, {
"Status": "1",
"Trend": "decrease",
"Space": "HCR"
}]
So can someone tell where I am going wrong and how would I go about displaying any of the components of the file in the console. I essentially want to use one of the values in the file, say status, to call on another function.
So something like: (psuedocode)
status.getvalue
.then(function)
if status > 3
console.log (place is crowded)

Okay so here you're trying to read a file on your computer, from a device (iPhone/Android/Emulator/etc). This is simply not doable. The getFile call expects a path on the device.
So, either:
Store the JSON file on the device, or
Just require() the JSON file. E.g. var jsonFile = require('status.json') and it'll get read and parsed for you.

Add something like below code, might be your jsonFile.readText() is throwing error
p1.then(function(value) {
console.log(value); // "Success!"
throw 'oh, no!';
}).catch(function(e) {
console.log(e); // "oh, no!"
})
jsonFile.readText()
.then(function (content)
{
try {
jsonData = JSON.parse(content);
//console.log('Item:' + JSON.stringify(jsonData));
array = new observableArrayModule.ObservableArray(jsonData);
}
catch (err) {
console.log(err);
}
console.log('Item:' +JSON.stringify(jsonData));
})
.catch(function(e) {
console.log(e); // "oh, no!"
});

Related

Trying to read a JSON file with a JS script in HTML

I am trying to use my json file, busesNotArrived.json and put its contents in a <p>, however it is not working and the data in the JSON file is not displaying, here is my code:
<p>Buses Not Arrived:<br><br><span id="output"></p>
<script>
const fs = require('fs')
fs.readFile('json/busesNotArrived.json', 'utf8', (err, jsonString) => {
if (err) {
alert('Error reading Database:', err)
return
}
try {
const bus = JSON.parse(jsonString)
alert("Bus address is:", bus.busNumber)
document.getElementById('output').innerHTML = bus.BusNumber;
} catch(err) {
alert('Error parsing JSON string:', err)
}
})
</script>
Inside of my JSON file, this is what is stored:
{
"busRoute": 123123,
"busNumber": 123123
}
Javascript is not the same as node.js
require() is not a part of JavaScript standard and is not supported by browsers out of the box, it is the node.js module system.
You might need to directly include the modules; some of the modules might not work in the browser sandbox context.
Also, tools such as http://browserify.org/ might be useful.
And please put the error message too.
Well, I eventually figured it out, so like what #Ronnel said, you cannot use require() because that is node.js and not javascript, so you would have to use the fetch() api to get the .json file.
For anyone who would like to see the code, here it is:
<div id="myData" class='absolute1' onclick='notArrived()'><strong><u>Not Yet Arrived</u></strong><br><br></div>
<script>
fetch('json/busesNotArrived.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
var mainContainer = document.getElementById("myData");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = 'Bus Number: ' + data[i].busNumber + "<br>" + 'Bus Route:' + ' ' + data[i].busRoute + "<br><br>";
mainContainer.appendChild(div);
}
}
</script>
|| Sorry about the Indents :P ||
And also, here is what was in the .json file so you can work off of it:
[
{
"id": "1",
"busNumber": "4024",
"busRoute": "44444"
},
{
"id": "2",
"busNumber": "4044",
"busRoute": "4444"
},
{
"id": "3",
"busNumber": "5024",
"busRoute": "55555"
}
]
Good Luck using this!
If you wanted more explanation, here is where I got the code from:
(https://howtocreateapps.com/fetch-and-display-json-html-javascript/)

Loading undefined number of file contents with ajax by config only one sucess listener

i have a json config that has a array of objects, containing file names. and i need to load them in a row and have a event when all files are ready loaded for displaying them as code snippet on my homepage.
config.json:
{
"author": "TypedSource",
"date": "2017-04-16",
"files": [
{
"lang": "HTML",
"fileName": "sample.html.txt"
},
{
"lang": "PHP",
"fileName": "sample.php.txt"
},
]
}
TypeScript code:
$(document).ready(function(){
$.get('config.json')
.ready(function(data){
console.log('success on loading config');
$.when(
// i want to load every file here
// but this for can't work inside the $.when
// it is just pseudo code for explain what i want to do
for(let i = 0; i < data.files.length; i++) {
$.get(data.files[i].fileName);
}
}.then(
function(){
// success listener for all files loaded
console.log('success on loading all files');
console.log(arguments);
// now build the template for each response[0] and bind it to highlight.js code block
}
function(){
// error listener if a file can't be loaded
// ATTENTION: if an error occured, no single success is given
console.error('error on loading files');
console.log(arguments[0].responseText());
}
)
})
.fail(function(){
console.error('error on loading config file');
console.log(arguments[0].responseText);
});
});
$.get only accepts 1 url to load, $.when is the option i know, but normaly i have to assign every call inside the when by hand. does somebody know how to handle it?
Create an array of the request promises to pass to Promise.all() which won't resolve until all request promises have resolved
$.getJSON('config.json').then(function(config) {
var requests = config.files.map(function(file) {
return $.get(file.fileName);
});
Promise.all(requests).then(function(res) {
console.log(res)
res.forEach(function(txt) {
$('body').append('<p>' + txt + '</p>')
});
});
});
The order of the results array in Promise.all() will be the same as the files array order in your config file
DEMO

Uploading Avatar on Parse (using AngularParse Service)

{"name":"tfss-4dde4ec8-e678-495a-a5d0-d3e51f0bdafc-search-pic-img6.jpg","url":"http://files.parsetfss.com/d130ccda-cf9f-4264-999e-09305bed0fd1/tfss-4dde4ec8-e678-495a-a5d0-d3e51f0bdafc-search-pic-img6.jpg"}
This is the return Object, When I upload the file on the parse server. I want to use this object to store it on the Parse Class avatar column as type "file" not string. In short I am trying to store it as image file after uploading. I want to do it in Cloud Code javascript rather than on html javacript. I want to send the object to parse and store it as image file.
Here's my cloud code. I am new to parse a bit.
Parse.Cloud.beforeSave("editProfileweb", function(request) {
var avatar = request.object;
var user = request.user;
if (user) {
user.set("avatar",avatar);
user.save(null, {
success: function(user) {
response.success();
},
error: function(error) {
// Show the error message somewhere and let the user try again.
response.success();
}
});
} else {
response.error("User not authenticated");
} });
I guess this is what you are looking for
Object.set({columnName: {"name": File.name, "url": File.url, "__type": "File"}});

I am not getting the JSON data, though it is getting loaded properly, why does that happen so? It is showing blank alert box

Following is my code, I want to get the JSON data, I am doing a railway app in office 365 Napa, my JSON is getting loaded but not showing me the data, and I am passing station code that is passed in the string through which HMAC signature is generated by passing it in URL I get the JSON which I have to read,
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function ()
{
getUserName();
$("#button1").click(function()
{
paraupdate();
});
});
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
function paraupdate()
{
var str=""+$("#textbox1").val();
alert(""+str);
var message = str+"json539ff0f815ca697c681fe01d32ba52e3";
var secret = "<my private key>";
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
alert("crypto answer is " + crypto);
var siteurl="http://pnrbuddy.com/api/station_by_code/code/"+str+"/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/"+crypto;
$.getJSON(
siteurl,
function(data){
alert(data.message);
});
}
function getUserName()
{
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess()
{
$("#label1").html("Enter Station Code : ");
$("#button1").val("CLICK");
}
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
})();
The JSON response is:
{
"response_code": 200,
"stations": [
{
"name": "Kanpur Central",
"code": "CNB",
"state": "UP",
"zip": null,
"railway_zone": "",
"location": {
"lat‌​": "26.4528466",
"lng": "80.3237478"
},
"about_text": null,
"about_link": null
},
{
"name": "‌​Chandari",
"code": "CNBI",
"state": "UP",
"zip": null,
"railway_zone": "",
"location": {
"la‌​t": "26.4279135",
"lng": "80.3604594"
},
"about_text": null,
"about_link": null
}
]
}
You are trying to alert data.message but your JSON doesn't have a message property. Look at properties that actually exist in the data.
Loading mixed (insecure) active content on a secure page
Don't make Ajax requests to HTTP end points from HTTPS pages. The data isn't secure, can be intercepted and might compromise the security of the page (especially if JSONP gets used for cross-origin requests).

Load local JSON file into variable

I'm trying to load a .json file into a variable in javascript, but I can't get it to work. It's probably just a minor error but I can't find it.
Everything works just fine when I use static data like this:
var json = {
id: "whatever",
name: "start",
children: [{
"id": "0.9685",
"name": " contents:queue"
}, {
"id": "0.79281",
"name": " contents:mqq_error"
}
}]
}
I put everything that's in the {} in a content.json file and tried to load that into a local JavaScript variable as explained here: load json into variable.
var json = (function() {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "/content.json",
'dataType': "json",
'success': function(data) {
json = data;
}
});
return json;
})();
I ran it with the Chrome debugger and it always tells me that the value of the variable json is null. The content.json file resides in the same directory as the .js file that calls it.
What did I miss?
My solution, as answered here, is to use:
var json = require('./data.json'); //with path
The file is loaded only once, further requests use cache.
edit To avoid caching, here's the helper function from this blogpost given in the comments, using the fs module:
var readJson = (path, cb) => {
fs.readFile(require.resolve(path), (err, data) => {
if (err)
cb(err)
else
cb(null, JSON.parse(data))
})
}
For ES6/ES2015 you can import directly like:
// example.json
{
"name": "testing"
}
// ES6/ES2015
// app.js
import * as data from './example.json';
const {name} = data;
console.log(name); // output 'testing'
If you use Typescript, you may declare json module like:
// tying.d.ts
declare module "*.json" {
const value: any;
export default value;
}
Since Typescript 2.9+ you can add --resolveJsonModule compilerOptions in tsconfig.json
{
"compilerOptions": {
"target": "es5",
...
"resolveJsonModule": true,
...
},
...
}
If you pasted your object into content.json directly, it is invalid JSON. JSON keys and values must be wrapped in double quotes (" not ') unless the value is numeric, boolean, null, or composite (array or object). JSON cannot contain functions or undefined values. Below is your object as valid JSON.
{
"id": "whatever",
"name": "start",
"children": [
{
"id": "0.9685",
"name": " contents:queue"
},
{
"id": "0.79281",
"name": " contents:mqq_error"
}
]
}
You also had an extra }.
A solution without require or fs:
var json = []
fetch('./content.json').then(response => json = response.json())
The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.
You can load it using var fs = require('fs');
Asynchronous
fs.readFile('./content.json', (err, data) => {
if (err)
console.log(err);
else {
var json = JSON.parse(data);
//your code using json object
}
})
Synchronous
var json = JSON.parse(fs.readFileSync('./content.json').toString());
There are two possible problems:
AJAX is asynchronous, so json will be undefined when you return from the outer function. When the file has been loaded, the callback function will set json to some value but at that time, nobody cares anymore.
I see that you tried to fix this with 'async': false. To check whether this works, add this line to the code and check your browser's console:
console.log(['json', json]);
The path might be wrong. Use the same path that you used to load your script in the HTML document. So if your script is js/script.js, use js/content.json
Some browsers can show you which URLs they tried to access and how that went (success/error codes, HTML headers, etc). Check your browser's development tools to see what happens.
For the given json format as in file ~/my-app/src/db/abc.json:
[
{
"name":"Ankit",
"id":1
},
{
"name":"Aditi",
"id":2
},
{
"name":"Avani",
"id":3
}
]
inorder to import to .js file like ~/my-app/src/app.js:
const json = require("./db/abc.json");
class Arena extends React.Component{
render(){
return(
json.map((user)=>
{
return(
<div>{user.name}</div>
)
}
)
}
);
}
}
export default Arena;
Output:
Ankit Aditi Avani
for free JSON files to work with go to https://jsonplaceholder.typicode.com/
and to import your JSON files try this
const dataframe1=require('./users.json');
console.log(dataframe1);
Answer from future.
In 2022, we have import assertions api for import json file in js file.
import myjson from "./myjson.json" assert { type: "json" };
console.log(myjson);
Browser support: till september 2022, only chromium based browsers and safari supported.
Read more at: v8 import assertions post
To export a specific value from output.json (containing json shared on question) file to a variable say VAR :
export VAR=$(jq -r '.children.id' output.json)

Categories

Resources