Having trouble getting data from a json file - json

I am trying to create a file explorer kind of project. I am using angularjs for this. The thing is I am having trouble to get the data from the json file which I created manually.
My json data
[
{
"id": 0,
"name": "Nature",
"images": [
{
"id": 0,
"src": "images/nature/01.jpg",
"thumb": "images/nature/01-thumb.jpg",
"name": "Nature View"
},
{
"id": 1,
"src": "images/nature/02.jpg",
"thumb": "images/nature/02-thumb.jpg",
"name": "Nature View"
},
{
"id": 2,
"src": "images/nature/03.jpg",
"thumb": "images/nature/03-thumb.jpg",
"name": "Nature View"
},
{
"id": 3,
"src": "images/nature/04.jpg",
"thumb": "images/nature/04-thumb.jpg",
"name": "Nature View"
}
]
},
{
"id": 1,
"name": "Lanscape",
"images": [
{
"id": 0,
"src": "images/landscape/01.jpg",
"thumb": "images/landscape/01-thumb.jpg",
"name": "Landscape View"
},
{
"id": 1,
"src": "images/landscape/02.jpg",
"thumb": "images/landscape/02-thumb.jpg",
"name": "Landscape View"
},
{
"id": 2,
"src": "images/landscape/03.jpg",
"thumb": "images/landscape/03-thumb.jpg",
"name": "Landscape View"
},
{
"id": 3,
"src": "images/landscape/04.jpg",
"thumb": "images/landscape/04-thumb.jpg",
"name": "Landscape View"
}
]
},
{
"id": 2,
"name": "Movies",
"images": [
{
"id": 0,
"src": "images/movies/01.jpg",
"thumb": "images/movies/01-thumb.jpg",
"name": "Ipsum View"
},
{
"id": 1,
"src": "images/movies/02.jpg",
"thumb": "images/movies/02-thumb.jpg",
"name": "Ipsum View"
},
{
"id": 2,
"src": "images/movies/03.jpg",
"thumb": "images/movies/03-thumb.jpg",
"name": "Ipsum View"
},
{
"id": 3,
"src": "images/movies/04.jpg",
"thumb": "images/movies/04-thumb.jpg",
"name": "Ipsum View"
}
]
}
]
It is a file explorer so thought it should have category name and it will have images in it. That's the reason this structure.
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-route.min.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
app.js
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'home.html',
controller: 'mainCtrl'
}).
when('/:id', {
templateUrl: 'detail.html',
controller: 'detailCtrl'
}).
otherwise({
redirectTo: '/'
});
});
app.controller('mainCtrl', function($http, $scope) {
$http.get('data.json').success(function (data) {
$scope.mainData = data;
});
});
app.controller('detailCtrl', function($http, $scope, $routeParams) {
$scope.id = $routeParams.id;
$http.get('data.json').success(function (data) {
angular.forEach(data, function (temp) {
$scope.mainData = temp.images;
});
});
});
home.html
<ul ng-repeat="data in mainData">
<li>{{data.name}}</li>
</ul>
detail.html
<div ng-repeat="data in mainData">
<h1>{{data.name}}</h1>
<img src="{{data.thumb}}" />
</div>
When I loop into images the data is displayed same for every id. What I am trying is when I click on nature I want the nature images and it's data to be displayed. I have created a plunkr http://plnkr.co/edit/aR7PM2KQw7XsCtGTYvtI?p=preview
Please help me with this as I'm having trouble understanding this one.

The problem is the detailCtrl you are allways setting mainData to last element. Quick Fix:
app.controller('detailCtrl', function($http, $scope, $routeParams) {
$scope.id = $routeParams.id;
$http.get('data.json').success(function (data) {
$scope.mainData = data[$scope.id].images;
});
});
Plunker Edited: http://plnkr.co/edit/3G2TFGvgfW4EihhS4oo4?p=preview
Extended Edit:
This works but is not the way to work in angular, you should wrap your data access into a factory, and then resolve the data model in the router before loading the view. Right now you are fetching the data each time, when you should only do this one time.

Related

How to add environment variables to app.json file

I have an app.json file in my Expo project. In this file I have two API keys (labeled API_KEY below) that I'd like to hide via environment variables.
How can I go about using environment variables instead of hard coding the API keys?
app.json
{
"expo": {
"name": "Closeout",
"slug": "Closeout",
"version": "1.0.0",
"orientation": "portrait",
"privacy": "hidden",
"notification": {
"icon": "./assets/images/notification-icon.png",
"color": "#000000",
"iosDisplayInForeground": true
},
"updates": {
"fallbackToCacheTimeout": 0
},
"assetBundlePatterns": ["**/*"],
"ios": {
"icon": "./assets/images/icon.png",
"buildNumber": "2",
"config": {
"googleMapsApiKey": "API_KEY"
}
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/images/icon.png",
"backgroundColor": "#000"
},
"versionCode": 5,
"useNextNotificationsApi": true,
"config": {
"googleMaps": {
"apiKey": "API_KEY"
}
},
"googleServicesFile": "./google-services.json"
}
}
}
I'm guessing you may have figured out a solution or tried something else by now. However, here is a solution to this issue, I hope it helps anyone facing the same challenge. This is from a typescript environment I'm implementing.
Create an app.config.ts file that overrides the content of the app.json file
import { ExpoConfig, ConfigContext } from '#expo/config';
import * as dotenv from 'dotenv';
// initialize dotenv
dotenv.config();
export default ({ config }: ConfigContext): ExpoConfig => ({
...config,
slug: 'my-app',
name: 'My App',
ios: {
supportsTablet: true,
bundleIdentifier: 'com.croon',
config: {
googleMapsApiKey: process.env.GOOGLE_CLOUD_API_KEY,
},
},
android: {
adaptiveIcon: {
foregroundImage: './assets/adaptive-icon.png',
backgroundColor: '#FFFFFF',
},
package: 'com.croon',
config: {
googleMaps: {
apiKey: process.env.GOOGLE_CLOUD_API_KEY,
},
},
},
});
Then you could leave the API entry blank on the app.json file.
{
"expo": {
"name": "Closeout",
"slug": "Closeout",
"version": "1.0.0",
"orientation": "portrait",
"privacy": "hidden",
"notification": {
"icon": "./assets/images/notification-icon.png",
"color": "#000000",
"iosDisplayInForeground": true
},
"updates": {
"fallbackToCacheTimeout": 0
},
"assetBundlePatterns": ["**/*"],
"ios": {
"icon": "./assets/images/icon.png",
"buildNumber": "2",
"config": {
"googleMapsApiKey": ""
}
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/images/icon.png",
"backgroundColor": "#000"
},
"versionCode": 5,
"useNextNotificationsApi": true,
"config": {
"googleMaps": {
"apiKey": ""
}
},
"googleServicesFile": "./google-services.json"
}
}
}
Remember to install the required dependencies
Cheers!

Getting remote data from JSON API using Axios and Vue

I'm very much at the beginning of my journey with Vue and JSON and I'm trying the following as an example.
I'm getting data from tastedive.com like so:
https://tastedive.com/api/similar?q=cannibal+corpse
Which gives me this:
{
"Similar": {
"Info": [
{
"Name": "Cannibal Corpse",
"Type": "music"
}
],
"Results": [
{
"Name": "Death",
"Type": "music"
},
{
"Name": "Deicide",
"Type": "music"
},
{
"Name": "Carcass",
"Type": "music"
},
{
"Name": "Slayer",
"Type": "music"
},
{
"Name": "Morbid Angel",
"Type": "music"
},
{
"Name": "Sepultura",
"Type": "music"
},
{
"Name": "Nile",
"Type": "music"
},
{
"Name": "Dying Fetus",
"Type": "music"
},
{
"Name": "Behemoth",
"Type": "music"
},
{
"Name": "Six Feet Under",
"Type": "music"
},
{
"Name": "Lamb Of God",
"Type": "music"
},
{
"Name": "Vader",
"Type": "music"
},
{
"Name": "Bloodbath",
"Type": "music"
},
{
"Name": "Amon Amarth",
"Type": "music"
},
{
"Name": "Obituary",
"Type": "music"
},
{
"Name": "Aborted",
"Type": "music"
},
{
"Name": "Immortal",
"Type": "music"
},
{
"Name": "Dark Funeral",
"Type": "music"
},
{
"Name": "Kreator",
"Type": "music"
},
{
"Name": "Decapitated",
"Type": "music"
}
]
}
}
Using the following in a file called app.js
const vm = new Vue({
el: '#app',
data: {
results: []
},
mounted() {
axios.get("https://tastedive.com/api/similar?q=cannibal+corpse")
.then(response => {this.results = response.data.results})
}
});
And my HTML looks like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello, world!</title>
</head>
<body>
<div class="container-xxl">
<h1>Hello, world!</h1>
</div>
<div class="container" id="app">
<div class="" v-for="result in results">
<div class="card">
<div class="card-divider">
{{ result.name }}
</div>
<div class="card-section">
<p>{{ result.type }}.</p>
</div>
</div>
</div>
</div>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="app.js"></script>
</body>
</html>
However, I'm not getting any results to the page.
Any guidance or help on what I'm doing wrong would be much appreciated. Thanks.
EDIT:
The main issue was pathing
response.data.results
Should've read:
response.data.Similar.Results
To reflect the JSON structure.
As noted in a comment below, I am getting CORS errors. I signed up for an API Key which hasn't fixed that issue. I have contacted tastedive.com asking them if they have any guidance on how to resolve this. I am using a browser plugin to get round the issue locally (https://chrome.google.com/webstore/detail/moesif-origin-cors-change/digfbfaphojjndkpccljibejjbppifbc)
Thanks for everyone's help.
I've updated the original question with the answer.

filter or find using lodash to find an object then use the nested array

I have the following json
{
"records": [
{},
{},
{},
{},
{},
{},
{},
{},
{
"id": "recoEidAQO7qiu7M9",
"fields": {
"Room": "Exterior",
"img": [
{
"id": "attVi68pAaCpX1fDQ",
"url": "https://dl.airtable.com/7munMtXcSK6WHDtMFEqA_IMG_0877%20New%20paint%20(1024x768).jpg",
"filename": "IMG_0877 New paint (1024x768).jpg",
"size": 566394,
"type": "image/jpeg",
"thumbnails": {
"small": {
"url": "https://dl.airtable.com/uFr8bJcSqyPFoe6n91EA_small_IMG_0877%20New%20paint%20(1024x768).jpg",
"width": 48,
"height": 36
},
"large": {
"url": "https://dl.airtable.com/zfgQJqL7Si2Vi9kZe3Bx_large_IMG_0877%20New%20paint%20(1024x768).jpg",
"width": 512,
"height": 512
}
}
}
]
},
"createdTime": "2016-08-16T21:29:37.000Z"
}
]
}
I'm attempting to use lodash. I'm trying get the url for the value 'Exterior' so that with jquery I can concatenate and build the following
$('wrapper').css('background-image' , 'url('+url+')')
Thanks in advance
You can use a combination of find and get in order to get the url:
var obj = _.find(json.records, function(el) {
return _.get(el, 'fields.Room') === 'Exterior';
});
var url = _.get(obj, 'fields.img[0].url');
var json = {
"records": [
{},
{},
{},
{},
{},
{},
{},
{},
{
"id": "recoEidAQO7qiu7M9",
"fields": {
"Room": "Exterior",
"img": [
{
"id": "attVi68pAaCpX1fDQ",
"url": "https://dl.airtable.com/7munMtXcSK6WHDtMFEqA_IMG_0877%20New%20paint%20(1024x768).jpg",
"filename": "IMG_0877 New paint (1024x768).jpg",
"size": 566394,
"type": "image/jpeg",
"thumbnails": {
"small": {
"url": "https://dl.airtable.com/uFr8bJcSqyPFoe6n91EA_small_IMG_0877%20New%20paint%20(1024x768).jpg",
"width": 48,
"height": 36
},
"large": {
"url": "https://dl.airtable.com/zfgQJqL7Si2Vi9kZe3Bx_large_IMG_0877%20New%20paint%20(1024x768).jpg",
"width": 512,
"height": 512
}
}
}
]
},
"createdTime": "2016-08-16T21:29:37.000Z"
}
]
};
var obj = _.find(json.records, function(el) {
return _.get(el, 'fields.Room') === 'Exterior';
});
var url = _.get(obj, 'fields.img[0].url');
console.log(url);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Data Table : Table has no columns

I am getting Table has no columns.× issue and i am not able to figure out why... Can you please help me understand whats wrong?
My HTML:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "<JSON URL>",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
JAVA CODE:
I am using code similar to one presented in the example
https://github.com/google/google-visualization-java/blob/master/examples/src/java/SimpleExampleServlet.java
MY JSON :
{
"rows":[
{
"cells":[
{
"value":{"value":"A","objectToFormat":"A","null":false,"type":"TEXT"},
"formattedValue":null,
"customProperties":{},
"null":false,
"type":"TEXT"
},
{
"value":{"value":"1","objectToFormat":"1","null":false,"type":"TEXT"},
"formattedValue":null,
"customProperties":{},
"null":false,
"type":"TEXT"
}
],
"customProperties":{}
},
{
"cells":[
{
"value":{"value":"B","objectToFormat":"B","null":false,"type":"TEXT"},
"formattedValue":null,
"customProperties":{},
"null":false,
"type":"TEXT"
},
{
"value":{"value":"0","objectToFormat":"0","null":false,"type":"TEXT"},
"formattedValue":null,
"customProperties":{},
"null":false,
"type":"TEXT"
}
],
"customProperties":{}
}
],
"customProperties":{},
"warnings":[],
"localeForUserMessages":null,
"numberOfRows":2,
"numberOfColumns":2,
"columnDescriptions":[
{"id":"Option","type":"TEXT","label":"Option","pattern":"","customProperties":{}},
{"id":"Count","type":"TEXT","label":"Count","pattern":"","customProperties":{}}
]
}
As were noted, google.visualization.DataTable expects JSON data to be provided in the format that is different from the one specified in question. Basically there are two options available:
modify Java servlet to generate JSON in format supported by google.visualization.DataTable
convert the generated JSON data
Below is demonstrated how to convert the provided JSON data to be compatible with google.visualization.DataTable(second option)
// Load the Visualization API and the piechart package.
google.load('visualization', '1', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
/*var jsonData = $.ajax({
url: "<JSON URL>",
dataType: "json",
async: false
}).responseText;*/
var jsonData = {
"rows": [
{
"cells": [
{
"value": { "value": "A", "objectToFormat": "A", "null": false, "type": "TEXT" },
"formattedValue": null,
"customProperties": {},
"null": false,
"type": "TEXT"
},
{
"value": { "value": "1", "objectToFormat": "1", "null": false, "type": "TEXT" },
"formattedValue": null,
"customProperties": {},
"null": false,
"type": "TEXT"
}
],
"customProperties": {}
},
{
"cells": [
{
"value": { "value": "B", "objectToFormat": "B", "null": false, "type": "TEXT" },
"formattedValue": null,
"customProperties": {},
"null": false,
"type": "TEXT"
},
{
"value": { "value": "0", "objectToFormat": "0", "null": false, "type": "TEXT" },
"formattedValue": null,
"customProperties": {},
"null": false,
"type": "TEXT"
}
],
"customProperties": {}
}
],
"customProperties": {},
"warnings": [],
"localeForUserMessages": null,
"numberOfRows": 2,
"numberOfColumns": 2,
"columnDescriptions": [
{ "id": "Option", "type": "TEXT", "label": "Option", "pattern": "", "customProperties": {} },
{ "id": "Count", "type": "TEXT", "label": "Count", "pattern": "", "customProperties": {} }
]
};
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(convertToDataTableJson(jsonData));
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, { width: 400, height: 240 });
}
function convertToDataTableJson(json)
{
var outJson = { cols: [], rows: []};
json.columnDescriptions.forEach(function(c){
outJson.cols.push({ "id": c.id, "label": c.label, "pattern": c.pattern, "type": c.type == "TEXT" ? "string" : "number" });
});
json.rows.forEach(function(r){
var cells = {c : []};
r.cells.forEach(function(c){
cells.c.push({ "v": c.value.value, "f": null });
});
outJson.rows.push(cells);
});
return outJson;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<div id="chart_div"></div>

I didnot get the data completely from the JSON into angularjs

I was write the code for displaying country details, but i didnot get the complete details from the json, why is this happen, is there any wrong with the syntax? I got only country name and population from the output.
<!DOCTYPE HTML>
<html ng-app='myApp'>
<head>
<title>search using filters</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.js"></script>
<script src="//ajax.googleapis.com/
ajax/libs/angularjs/1.2.12/angular-route.js"> </script>
<link rel="stylesheet" href="bootstrap-3.2.0-dist/css/bootstrap.css" />
<script type="text/javascript">
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider)
{
$routeProvider.
when('/',{
templateUrl:'partial2.html',
controller:'MyCtrl'
}).
when('/:countryName',{
templateUrl:'partial1.html',
controller:'oCtrl'
}).
otherwise({
redirectTo:'/'
});
});
myApp.controller('MyCtrl',function($scope,$http) {
$http.get('/Zjs/data/countries.json').success(function(data){
$scope.countries=data;
});
});
myApp.controller('oCtrl',function($scope,$routeParams,$http)
{
$scope.name=$routeParams.countryName;
$http.get('/Zjs/data/countries.json').success(function(data){
$scope.country=data.filter(function(entry){
return entry.name===$scope.name;
})[0];
});
});
</script>
</head>
<body>
<div class="container" ng-view></div>
</body>
</html>
//partial1
<h1>{{country.name}}</h1>
<ul>
<li>Image:<img ng-src="{{country.Image}}" width="300" height="300"></img></li>
<li>Population:{{country.population | number }}</li>
<li>Capital: {{country.cap}}</li>
</ul>
//partial2
<ul>
<li ng-repeat="con in countries"><a href="#/{{con.name}}" >{{con.name}}</a></li>
<ul>
//countries.json
[
{"name":"india", "population":12345682700,
"cap":"New Delhi",
"Image":"http://www.dollsofindia.com/
images/products/nature-posters/village-scene-DH52_l.jpg"},
{"cap":"Tokyo","name":"japan", "population":1382700,
"Image":"file:///C:/Users/USER/Pictures/er/gettt/3.jpg"
},
{"name":"South korea", "population":13700,
"cap":"Seoul","Image":"C:\Users\USER\Pictures\er\gettt\6.jpg"},
{"name":"iran", "population":132700,
"cap":"Tehran","Image":"C:\Users\USER\Pictures\er\gettt\9.jpg"},
{"name":"russia", "population":1485682700,
"cap":"Moscow","Image":"C:\Users\USER\Pictures\er\gettt\11.jpg"}
]
You have got unescaped backslashes in your json file, I would start by eliminating those and see where that takes you, when I tried your code, resolving that worked for me at least.
[
{
"name": "india",
"population": 12345682700,
"cap": "New Delhi",
"Image": "http://www.dollsofindia.com/images/products/nature-posters/village-scene-DH52_l.jpg"
},
{
"cap": "Tokyo",
"name": "japan",
"population": 1382700,
"Image": "file:///C:/Users/USER/Pictures/er/gettt/3.jpg"
},
{
"name": "South korea",
"population": 13700,
"cap": "Seoul",
"Image": "file:///C:/Users/USER/Pictures/er/gettt/6.jpg"
},
{
"name": "iran",
"population": 132700,
"cap": "Tehran",
"Image": "file:///C:/Users/USER/Pictures/er/gettt/9.jpg"
},
{
"name": "russia",
"population": 1485682700,
"cap": "Moscow",
"Image": "file:///C:/Users/USER/Pictures/er/gettt/11.jpg"
}
]
your json was not a valid one.. so please use this
[
{
"name": "india",
"population": 12345682700,
"cap": "New Delhi",
"Image": "http://www.dollsofindia.com/images/products/nature-posters/village-scene-DH52_l.jpg"
},
{
"cap": "Tokyo",
"name": "japan",
"population": 1382700,
"Image": "file: ///C: /Users/USER/Pictures/er/gettt/3.jpg"
},
{
"name": "Southkorea",
"population": 13700,
"cap": "Seoul",
"Image": "file: ///C: /Users/USER/Pictures/er/gettt/6.jpg"
},
{
"name": "iran",
"population": 132700,
"cap": "Tehran",
"Image": "file: ///C: /Users/USER/Pictures/er/gettt/9.jpg"
},
{
"name": "russia",
"population": 1485682700,
"cap": "Moscow",
"Image": "file: ///C: /Users/USER/Pictures/er/gettt/11.jpg"
}
]
you can test your json data is valid or not by using http://jsonlint.com