How to convert XML to JSON with react - json

I have an API that provides me XML data, and i want to convert that XML data from the API into JSON. Can anyone help me wiht that problem?
I'm using Expo to creat a app. I tried to use nodemoduls, but when i tried that I alwas get an error "It failed because React Native does not include the Node standard library" The code belwo dosen't work
import { View, Text, ActivityIndicator } from 'react-native'
import { fetch } from "fetch";
const furl = 'https://skimap.org/Regions/view/346.xml';
const xmlToJson = require('xml-to-json-stream');
const parser = xmlToJson({attributeMode: true});
export default class RegionList extends PureComponent {
state = { regions: [] };
async componentWillMount() {
fetch(furl).then(response => parser.xmlToJson(response, (err,json)=>{
if(err){
console.log(err);
}
}))
.then( (response) => this.setState({regions: response}));
}

Try this:
import {Xml2Json} from 'react-native-xml-to-json';
fetch(furl).then(response =>
Xml2Json.toJson(response, data => {
console.log("Data = ", data);
}).then( (response) => this.setState({regions: data})
);

Related

Import csv file and send to backend

I try to create a redux-react app where the users can import an csv-file that later is stored in a database. Right now I am working on the frontend where I want to create a code where the user can chose a csv file from their computer that they want to download and then the file is sent to the backend. I have therfore used the csvReader to read the csv-file but I don't know how to send the data to the backend. I am using nestJS in the backend. I want to send the whole csv-file in one go but i dont know how to tackle the problem. I am a beginner :))) Do you know how to solve my problem?
I can't help you with react but maybe this NestJS part can help you. You can use multer to config your api and setting a store path.
Create multer options
// multer.ts
const excelMimeTypes = [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/wps-office.xlsx',
'application/vnd.ms-excel',
];
export const multerOptions = {
fileFilter: (req: any, file: any, cb: any) => {
const mimeType = excelMimeTypes.find(im => im === file.mimetype);
if (mimeType) {
cb(null, true);
} else {
cb(new HttpException(`Unsupported file type ${extname(file.originalname)}`, HttpStatus.BAD_REQUEST), false);
}
},
storage: diskStorage({
destination: (req: any, file: any, cb: any) => {
const uploadPath = '/upload'; // use env var
if (!existsSync(uploadPath)) {
mkdirSync(uploadPath); // create if not exists
}
cb(null, uploadPath);
},
filename: (req: any, file: any, cb: any) => {
cb(null, file.originalname);
},
}),
};
Import multerOption recent created and use FileInterceptor and UploadedFile decorator to get the file.
#Post()
#UseInterceptors(FileInterceptor('file', multerOptions))
uploadFile(#UploadedFile() file) {
console.log(file) // call service or whathever to manage uploaded file.. handleFile in the example below..
}
Manage file (example) using xlsx library.
handleFile(file: any): Promise<any> {
return new Promise(async (resolve: (result: any) => void, reject: (reason: any) => void): Promise<void> => {
try {
const workbook = XLSX.readFile(`${uploadLocation}/${file.filename}`);
resolve(workbook.Sheets[sheetName]);
} catch (error) {
reject(error);
}
});
}
I hope it helps!

JSON data from S3 text file using React

I'm trying to get JSON data from an s3 bucket using React (in a Gatsby project).
This is my code.
import React from 'react';
function getJson() {
return fetch("http://secstat.info/testthechartdata.json")
.then((response) => response.json())
.then((responseJson) => {
return <div>{responseJson[0]}</div>;
})
.catch((error) => {
console.error(error);
});
};
export default getJson;
This is the error I get.
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
How should I do this? There is probably an easy way to do this in Gatsby but I was going to use React.
Your code has 2 issues:
You can't return a component that waits to Promise.
Fetching a cross domain assets will require CORS headers in your S3
You should refactor it to something like this:
import React, { useState, useEffect } from 'react';
function getJson() {
return fetch('http://secstat.info/testthechartdata.json')
.then(response => response.json())
.catch(error => {
console.error(error);
});
}
const MyComp = () => {
const [list, setList] = useState([]);
useEffect(() => {
getJson().then(list => setList(list));
}, []);
return (
<ul>
{list.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
export default MyComp;

can't fetch local json file in electron-vue

I try to fetch a local json file in my project.
Tried the following:
import axios from 'axios';
import userDataJson from './../data/userData.json';
export const userDataControllerMixin = {
data() {
return {
users: [],
};
},
mounted() {
this.getUsers();
},
methods: {
getUsers() {
// TODO: load userObj.json initial to prevent reset the userData.json all the time
fetch(userDataJson)
.then((response) => {
console.log(response);
}).catch((err) => {
console.log(err);
});
};
i also tried it with axios before but they all lead into this error msg:
GET http://localhost:9080/[object%20Object] 404 (Not Found)
What am i doing wrong? Looks like a config issue.
You dont need to call fetch method anymore since you are importing your json data from the file. What you can do is, since you are already importing the json data, then when the component is mounted just assign the json data to the user array:
data() {
return {
users: [],
};
},
mounted() {
this.users = JSON.parse(userDataJson)
},
....
}

accessing the json data from axios call in vue

I setup a fake mocke server in postman to get som test data for my vue applikation. This is what i am getting from the server:
I want to access the data information but i am having hard time doing so. This is the code that i am using:
<template>
<div class="admin">
<h1>This is admin page area</h1>
<JsonEditor :objData="config" v-model="config" ></JsonEditor>
</div>
</template>
<script>
import{getConfig} from "../utils/network";
import Vue from 'vue'
import JsonEditor from 'vue-json-edit'
Vue.use(JsonEditor)
export default{
data: function () {
return {
config:{}
}
},
created:function(){
getConfig()
.then(response => {
console.log(response)
this.config = response;
})
.catch(err => {
console.log(err)
})
}
}
</script>
I have tried doing response.data but did not work. I am feeding this to the json editor but it is currently not being able to show the json. Its empty. This is my network call code:
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
const getConfig = () =>{
return Vue.axios.get('https://8db51a11-752e-4d64-b237-8195055fbf26.mock.pstmn.io')
};
//Export getConfig so other classes can use it
export{
getConfig
}
What am i missing?
You can also try providing a then statement:
const getConfig = () =>{
Vue.axios.get('https://8db51a11-752e-4d64-b237-8195055fbf26.mock.pstmn.io').then(response => {
return response.data});
};

Making an API call in React

I am trying to make an API call in React to return JSON data but I am a bit confused on how to go about this. My API code, in a file API.js, looks like this:
import mockRequests from './requests.json'
export const getRequestsSync = () => mockRequests
export const getRequests = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(mockRequests), 500)
})
It is retrieving JSON data formatted like this:
{
"id": 1,
"title": "Request from Nancy",
"updated_at": "2015-08-15 12:27:01 -0600",
"created_at": "2015-08-12 08:27:01 -0600",
"status": "Denied"
}
Currently my code to make the API call looks like this:
import React from 'react'
const API = './Api.js'
const Requests = () => ''
export default Requests
I've looked at several examples and am still a bit confused by how to go about this. If anyone could point me in the right direction, it would be greatly appreciated.
EDIT: In most examples I've seen, fetch looks like the best way to go about it, though I'm struggling with the syntax
Here is a simple example using a live API (https://randomuser.me/)... It returns an array of objects like in your example:
import React from 'react';
class App extends React.Component {
state = { people: [], isLoading: true, error: null };
async componentDidMount() {
try {
const response = await fetch('https://randomuser.me/api/');
const data = await response.json();
this.setState({ people: data.results, isLoading: false });
} catch (error) {
this.setState({ error: error.message, isLoading: false });
}
}
renderPerson = () => {
const { people, isLoading, error } = this.state;
if (error) {
return <div>{error}</div>;
}
if (isLoading) {
return <div>Loading...</div>;
}
return people.map(person => (
<div key={person.id.value}>
<img src={person.picture.medium} alt="avatar" />
<p>First Name: {person.name.first}</p>
<p> Last Name: {person.name.last}</p>
</div>
));
};
render() {
return <div>{this.renderPerson()}</div>;
}
}
export default App;
Does it make sense? Should be pretty straight forward...
Live Demo Here: https://jsfiddle.net/o2gwap6b/
You will want to do something like this:
var url = 'https://myAPI.example.com/myData';
fetch(url).then((response) => response.json())
.then(function(data) { /* do stuff with your JSON data */})
.catch((error) => console.log(error));
Mozilla has extremely good documentation on using fetch here that I highly recommend you read.
The data parameter in the second .then will be an object parsed from the JSON response you got and you can access properties on it by just using the property label as was in the JSON. For example data.title would be "Request from Nancy".
If you are struggling with fetch, Axios has a much simpler API to work with.
Try this in your API.js file (of course install axios first with npm i --save axios):
import axios from 'axios'
import mockRequests from './requests.json'
export const getRequests = (url) => {
if (url) {
return axios.get(url).then(res => res.data)
}
return new Promise((resolve, reject) => { // you need to return the promise
setTimeout(() => resolve(mockRequests), 500)
})
})
In your component, you can access the getRequests function like so
import React, { Component } from 'react'
import { getRequests } from './API.js'
class App extends Component {
state = {
data: null
}
componentWillMount() {
getRequests('http://somedomain.com/coolstuff.json').then(data => {
console.log(data)
this.setState({ data })
})
}
render() {
if (!this.state.data) return null
return (
<div className='App'>
{this.state.data.title}
</div>
)
}
}
export default App