Json data not showing in vuejs - json

I am making a vue app. I put a .json file in static directory. I am trying to read it in the default HelloWorld.vue file. But it's not showing in the browser. Here is what it shows in the browser:
My json file looks like this:
{
"status": "success",
"message": "Successfully retrieved all registered applications",
"Applications": [
{
"ApplicationID": "74382DOD",
"ApplicationName": "OIMInstance2",
"ApplicationType": "OIM",
"APIToken": "ZM8R4FRiZWWKbl235u06zbArCdOBPlEKhqHQO8Y9RJ2HgBPC+cZgbIli8fFuNZaey/2tJciJuILIWIn24WTjGA=="
},
{
"ApplicationID": "943ODA6G",
"ApplicationName": "LDAPInstance2",
"ApplicationType": "LDAP",
"APIToken": "R9lDEW5dnN6TZg2sefEEzS6LWMNmFh4iLHMu47LmAsusHl0bZuh2rktSlXqSZRdHHEWq7sP4Xsdy6xNtDYE8xw=="
}
]
}
My code in HelloWorld.vue is:
<template>
<div>
<h1>APPLICATION REGISTRATION</h1>
<div v-for="udata in userData">
Id : {{ udata.ApplicationID }}
</div>
</div>
</template>
<script>
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
export default {
name: 'HelloWorld',
data () {
return {
userData: []
}
},
created: function() {
axios.get('../../static/mockdata.json')
.then(response => {
this.userData = response.data
})
.catch(e => {
//this.errors.push(e)
})
}
}
</script>
Is there anything wrong with my code? How do I show the json data in the browser?

You need to iterate through applications object.Hence in order to get applicationId you will need to set data accordingly by only adding applications data in your userData variable.
Do as below.
this.userData = response.data.Applications

Related

Trying to load json through Vue Axios

I'm trying to include a local JSON file from the static directory called blogs.json which has a load of blogs inside it.
I'm currently loading the blogs via Vue Axios which is a module I'm including in Nuxt JS.
Currently, the blogs are being loaded from the json file perfectly fine, however there is a noticeable few ms delay before the blogs are loaded, I'm trying to figure out a better approach to load the json file and populate the blogs array listed inside data()
This is my current code:
<script>
import PageBanner from '~/components/PageBanner';
export default {
head: {
title: 'Site Title: Blog',
meta: [
{ hid: 'description', name: 'description', content: 'Site description' }
]
},
components: {
PageBanner
},
data () {
return {
blogs: [],
isLoading: true
}
},
created () {
this.axios.get("/articles/blogs.json").then((response) => {
this.blogs = response.data
this.isLoading = false
})
}
}
</script>
This works just fine, but how could I modify this to load the json more quickly?
Just import it, do this and it should work God willing:
<template>
<div>
<!-- There should be no delay -->
{{blogs}}
</div>
<template>
<script>
import PageBanner from '~/components/PageBanner';
import blogsFromJson from '~/articles/blogs.json'; // Or wherever it is found
export default {
head: {
title: 'Site Title: Blog',
meta: [
{ hid: 'description', name: 'description', content: 'Site description' }
]
},
components: {
PageBanner
},
data () {
return {
blogs: blogsFromJson, // Just set it here
isLoading: true
}
},
/* No need for this anymore
created () {
this.axios.get("/articles/blogs.json").then((response) => {
this.blogs = response.data
this.isLoading = false
})
}
*/
}
</script>

Fetching data from local .json file in react.js returns multiple errors

I have a json file named autofill.json and it's created to autofill a search bar when pressed on.
the autofill.json is a test file that's why it looks like this.
[
{
"a": {
"apple": {
"name": "apple",
"href": "https://www.apple.com/"
},
"armadillo": {
"name": "armadillo",
"href": "https://www.armadillo.com/"
}
},
"b": {
"box": {
"name": "apple",
"href": "https://www.berserk.com/"
},
"berserk": {
"name": "berserk",
"href": "https://www.berserk.com/"
}
}
}
]
The .json file is then fetched in the file named FetchAndParseResults.js
import fetch from 'isomorphic-fetch'
const FetchAndParseResults = (url) => {
return fetch(url).then(response => {
const parsedJson = response.json()
return parsedJson
})
}
export default FetchAndParseResults
The data that gets fetched is used in searchcontainer.js where everything gets placed in, the search etc.
import React from 'react'
import Searchbar from './index.js'
import FetchAndParseResults from './FetchAndParseResults.js'
class SearchContainer extends React.Component {
state = {
results: []
}
performSearch = event => {
return FetchAndParseResults('static/autofill.json').then(data => {
this.setState({ results: data })
})
}
render () {
console.log('performSearch event', this.performSearch)
console.log('data inside performSearch', this.state.results)
return (
<Searchbar
performSearch={this.performSearch}
results={this.state.results}
/>
)
}
}
export default SearchContainer
Then to map through the data that is in autofill.json there is a file named autofill.js
import React from 'react'
import PropTypes from 'prop-types'
import Styles from './searchbar.scss'
const AutoFill = (props) => {
console.log('proppppppsss', props)
const results = props.results || []
return (
<ul className={Styles.searchUl}>
{results.map(({ name, href }) => (
<li className={Styles.searchLi} key={href}>
<a className={Styles.searchA} href={href} target='_blank' rel='noopener noreferrer' key={href}>
{name}
</a>
</li>
))}
</ul>
)
}
AutoFill.propTypes = {
results: PropTypes.array
}
export default AutoFill
the Searchbar component in (index.js) that is being used in searchcontainer.js
import React from 'react'
import Styles from './searchbar.scss'
import Icon from '../../components/icon/icon'
import Search from '../../components/form-input/search'
import AutoFill from './autofill'
import PropTypes from 'prop-types'
export default class Searchbar extends React.Component {
constructor (props) {
super(props)
this.state = {
className: Styles.input,
icon: Styles.icon__wrapper,
value: []
}
this.input = React.createRef()
}
openInput = () => {
this.setState({
className: Styles.input__active,
icon: Styles.iconWidth
}, () => {
this.input.focus()
})
this.props.onOpen && this.props.onOpen()
}
closeInput = () => {
this.setState({
className: Styles.input,
icon: Styles.icon__wrapper
})
this.props.onClose && this.props.onClose()
}
handleChange = event => {
let value = event.target.value
this.setState({ value })
this.props.performSearch(value)
}
handleSubmit = event => {
event.preventDefault()
}
render () {
console.log('results', this.props.results)
console.log('state.value', this.state.value)
return (
<div>
<form onSubmit={this.handleSubmit} className={Styles.search}>
<div className={this.state.icon}>
<Icon className={Styles.icon__wrapper} iconName='faSearch' onClick={this.openInput} />
</div>
<Search autoComplete='off' value={this.state.value} onChange={this.handleChange} id='search' tabIndex='0' myref={input => { this.input = input }} className={this.state.className} onBlur={this.closeInput} placeholder='Search' />
</form>
<div>
<AutoFill results={this.props.results} />
</div>
</div>
)
}
}
Search.propTypes = {
performSearch: PropTypes.func,
results: PropTypes.array
}
When i try to refer to a what is in the json file from the search i receive the error,
GET http://localhost:3000/[object%20Object] 404 (Not Found)
And
about:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON
at position 0
The second error is fixed by doing
const parsedJson = response.text(
instead of
const parsedJson = response.json()
to get more information where/what the error takes place. But by doing this i receive the error,
searchcontainer.js:12 Uncaught (in promise) TypeError: Cannot read property 'results' of undefined
I've tried to run it from npm build instead of running it in a dev environment which didn't fix it.
I read that a mock url should work but then again i want to acces it from a file and not from a url?
Any help would be highly appreciated and looked into.
The problem is most likely in the fetch call. If you look at the error message GET http://localhost:3000/[object%20Object] 404 (Not Found)
You can see that it is trying to append an object to the URL localhost:3000/.
You are getting the Unexpected token < in JSON at position 0 error because the response of your fetch request is probably a 404 page. The < is most likely the first char of <html>
To access the JSON object in your React files, you can simply do an importation like so;
import * as autofillData from 'autofill.json';
It will be returned as a JSON object.
I believe you are using the isomorphic-fetch package wrongly, if you look at their source code, https://github.com/matthew-andrews/isomorphic-fetch/blob/master/fetch-npm-node.js#L5 , they are accepting a URL to make a call to the API URL which will return a promise or a JSON object depending on the implementation of the API that you are calling.
If you were to dive deeper into the open-source code here (https://github.com/matthew-andrews/isomorphic-fetch/blob/master/fetch-npm-node.js#L8) , you will notice that isomorphic-fetch package is using another package node-fetch to do their fetch call, which accepts the API URL and the method request options to call the API with. (As stated here; https://github.com/bitinn/node-fetch/blob/master/src/index.js#L34)
To continue with your test, perhaps this might be the solution you'd prefer?
import fetch from 'isomorphic-fetch';
import * as autofillData from 'autofill.json'; //test data
const FetchResults = event => {
return fetch('/https://jsonplaceholder.typicode.com/todos/1'') //mockURL, to be replaced with real API
.then(response => {
// const parsedJson = response.json(); // TODO: un-comment this line when the real API url is usable
const parsedJson = autofillData; // TODO: remove this line when mocking is done and the real API URL is ready
return parsedJson;
})
}
export default FetchResults;
To have a mock URL placeholder, I would suggest https://jsonplaceholder.typicode.com/ to prevent your fetch result to return an unexpected error during test mocking.
Hope this is helpful.
The question has been solved, The main issue was with defining const names such as const results = [] which should've been const results = props.results || [].
The code has been updated incase you have problems aswell.

How to render JSON response as dropdown list in React

I'm currently trying to take some JSON data that I've received from an API and put that into a dropdown in a very simple React application.
This is my DropDown component thus far:
import React from 'react';
var values;
fetch('http://localhost:8080/values')
.then(function(res) {
return res.json();
}).then(function(json) {
values = json;
console.log(values);
});
class DropDown extends React.Component {
render(){
return <div className="drop-down">
<p>I would like to render a dropdown here from the values object</p>
</div>;
}
}
export default DropDown;
Any my JSON looks like this:
{
"values":[
{
"id":0,
"name":"Jeff"
},
{
"id":1,
"name":"Joe"
},
{
"id":2,
"name":"John"
},
{
"id":3,
"name":"Billy"
},
{
"id":4,
"name":"Horace"
},
{
"id":5,
"name":"Greg"
}
]
}
I'd like the dropdown options to correspond to the 'name' of each element, and the 'id' to be used as an element identifier when an event is triggered by selecting an option. Any advice on getting this data into a dropdown which responds to user input would be greatly appreciated.
Call the API in componentDidMount lifecycle function of your React component and then save the response in state and then render the Select dropdown
import React from 'react';
class DropDown extends React.Component {
state = {
values: []
}
componentDidMount() {
fetch('http://localhost:8080/values')
.then(function(res) {
return res.json();
}).then((json)=> {
this.setState({
values: json
})
});
}
render(){
return <div className="drop-down">
<p>I would like to render a dropdown here from the values object</p>
<select>{
this.state.values.map((obj) => {
return <option value={obj.id}>{obj.name}</option>
})
}</select>
</div>;
}
}
export default DropDown;
You could do something like this:
import React from 'react';
var values;
class DropDown extends React.Component {
constructor(){
super();
this.state = {
options: []
}
}
componentDidMount(){
this.fetchOptions()
}
fetchOptions(){
fetch('http://localhost:8080/values')
.then((res) => {
return res.json();
}).then((json) => {
values = json;
this.setState({options: values.values})
console.log(values);
});
}
render(){
return <div className="drop-down">
<select>
{ this.state.options.map((option, key) => <option key={key} >{option}</option>) }
</select>
</div>;
}
}
export default DropDown;
Basically you are initializing state and setting options to null.
You are then fetching your options when the component mounts in the browser. These values are set to your state with this.setState().
Note: It is important to make any API calls in componentDidMount() and not componentWillMount(). If you call it in componentWillMount() the request will be made twice.
Then you render these options by mapping them in your render function
JSON FILE: terrifcalculatordata.json
[
{
"id": 1,
"name": "Vigo",
},
{
"id": 2,
"name": "Mercedes",
},
{
"id": 3,
"name": "Lexus",
},
{
"id": 4,
"name": "Buggati",
},
]
CODE:
1st import json file on top:
import calculatorData from "../static/data/terrifcalculatordata.json";
2nd in render method type this code:
<Form>
<FormGroup>
<Input
type="select"
onChange = {this.changeCarmodel}
value={this.state.changeCar}
>
{calculatorData.map((caldata, index) =>
<option
key={index}
value= {caldata.id}
> {caldata.name} </option>
)}
</Input>
</FormGroup>
</Form>
How to render JSON response as dropdown list in React.
export default class ExpenseNew extends Component {
constructor(){
super();
this.state={
PickerSelectedVal : '',
accountnameMain:[],
}
}
componentDidMount(){
var account_nam=[]
fetch('your Url', {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + your token }
})
.then((response) => response.json())
.then((customerselect) => {
// alert(JSON.stringify(customerselect))
global.customerdata = JSON.stringify(customerselect)
var customername = JSON.parse(customerdata);
//alert(JSON.stringify(customername));
for (i = 0; i < customername.cus_data.length; i++) {
var dataa = customername.cus_data[i]["account_name"];
account_nam.push(dataa)
}
this.setState({accountnameMain:account_nam});
})
.done();
}
render() {
return (
<Picker
selectedValue={this.state.PickerSelectedVal}
placeholder="Select your customer"
mode="dropdown"
iosIcon={<Icon name="arrow-down" />}
onValueChange={(itemValue, itemIndex) => this.setState({PickerSelectedVal: itemValue})} >
{this.state.accountnameMain.map((item, key)=>(
<Picker.Item label={item} value={item} key={key}/>)
)}
</Picker>
)
}
}

checking return json object for data typescript and angular2

so i have made a call to check and see if i return an object with actual data in it - I am not sure if i am doing this wrong but this is what i am trying.
Here is my get call i have made to my services - COMPONENT FILE:
resultData: any = [];
barChartLabels: any =[];
getData(){
this.dataService.getData().subscribe((data) => {
this.resultData = data;
for(let item of this.resultData) {
this.barChartLabels.push(item.name);
}
}
}
I am currently seeing this.resultData in my console but know after pushing item's name into another array which is used in binding in my html it is not being displayed.
Here is my service call - SERVICE FILE:
getData(){
return this.http.get('my url')
.map((res:Response) => res.json());
}
Here is also what i have in my json file:
[
{
"id": 1,
"name": "Test 1",
"score": 34
},
{
"id": 2,
"name": "Test 2",
"score": 92
}
]
This is my html:
<canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]="barChartType">
</canvas>
This may have transitioned into a different topic now.
If you really want it to be in the component, then the code needs to be in the body of the arrow function. Something like this:
getData(){
this.dataService.getData().subscribe(data => {
this.resultData = data;
for(let resultItem of this.resultData){
console.log(resultItem);
}
})
}
This is because the subscribe is asynchronous. When the getData method first runs, this.resultData has no value. It isn't until the Http response is returned that this.resultData is set.
You can use the do operator to see the data that is returned. You could try something like this:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
...
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}

Can't access nested JSON data in my Vue Component

Im trying to figure out why I can't seem to access the following piece of JSON data in my Vue Component.
My project is setup using Vue-cli with the Webpack template and is roughly setup as follows when I run into the problem.
Data JSON
This file contains several projects
projects: [
{
"slug": "page-url-slug",
"title": "Page title",
"image": {
"src": "/static/images/project-image.jpg",
"alt": "Alt text image"
}
}
]
Router
routes: [
{
path: '/work'
component: Work
},
{
path: '/work/:slug',
component: WorkItem,
props: (route) => ({
params: route.params
})
}
]
Component JS
export default {
props: [ 'params' ],
data () {
return {
project: {}
}
},
mounted () {
this.$http.get('/static/data.json')
.then((response) => {
let projects = response.data.projects
// Find data with same slug param
for (let i = 0; i < projects.length; i++) {
if (projects[i].slug === this.params.slug) {
this.project = projects[i]
return
}
}
// Else go back to parent route
this.$router.push('/work')
})
}
}
Component HTML
<template lang="html">
<div class="page">
<h1>{{ project.title }}</h1>
<img :src="project.image.src" alt="project.image.alt" />
</div>
</template>
When I try to access the project.image.src or the project.image.alt I keep getting the following error messages:
[Vue warn]: Error when rendering anonymous component at ...
Uncaught TypeError: Cannot read property 'src' of undefined
I am pretty new to Vuejs and I just can't seem to wrap my mind around the fact this happens.
You have to add null check as you are loading project asynchronously, like this:
<img :src="project && project.image && project.image.src" alt="project.image.alt" />
When this is being rendered, at that time project is not populated and it is still {}, which you set it in the beginning.