How to parse xml to Json ionic 2 - json

I have been on this problem for the past three days. I want to convert an XML which is retrieved via HTTP into JSON so I can display it in ionic 2. Here is my codes in a provider.. Any help will be much appreciated.. thank you!
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import * as xml2js from "xml2js";
#Injectable()
export class News {
constructor(public http: Http) { }
public getData() {
this
.http
.get('https://www.ug.edu.gh/news.xml')
.map(res => {
var cleanedString = res.toString().replace("\ufeff", "");
xml2js
.parseString(cleanedString, (error, result) => {
console.log(result);
return result;
});
})
.subscribe((data) => {
console.log(data)
}, (err) => {
console.log(err)
});
}
}

For Parsing xml to json in ionic 2
You can install the typings for xml2json now using the command
typings install xml2json --save
If it generate error like this
'typings' is not recognized as an internal or external command,
operable program or batch file.
Then first use this command to install typing
npm install typings -g
Then run previous command
typings install xml2json --save
Then it'll work fine.
Hope it work for you

You're almost there. Things go wrong when you return the data from parseString method. You just should use a temporary variable, assign the result from the parseString method and return that temporary variable like so:
// ...
.map(res => {
let cleanedString = res.toString().replace("\ufeff", "");
let jsonData;
xml2js
.parseString(cleanedString, (error, result) => {
if(error) {
console.error(error);
jsonData = error;
} else {
jsonData = result;
}
});
return jsonData;
}).subscribe((data) => {
// ...
A more in depth description and an alternative method is given here.

Related

Next JS Error serializing `.dehydratedState.queries[0].state.data.config.adapter` returned from `getServerSideProps

I am trying to use react-query to fetch data in getServerSideProps in Next JS but I keep getting this weird error:
Error: Error serializing `.dehydratedState.queries[0].state.data.config.adapter` returned from `getServerSideProps` in "/auth/google/callback".
Reason: `function` cannot be serialized as JSON. Please only return JSON serializable data types.
Here is my code:
// Packages
import { useRouter } from 'next/router'
import { dehydrate, QueryClient, useQuery } from 'react-query';
// APIs
import { completeGoogleAuth } from '../../../hooks/auth';
export async function getServerSideProps(context) {
const queryClient = new QueryClient()
await queryClient.prefetchQuery('completeGoogleAuth', () => completeGoogleAuth(context.query.code));
return {
props: {
dehydratedState: dehydrate(queryClient),
},
}
}
export default function Callback() {
const router = useRouter();
const { data } = useQuery('completeGoogleAuth', () => completeGoogleAuth(router.query.code))
return (
<>
Loading
</>
)
}
I have tried to use JSON.stringify(dehydrate(queryClient)) and also used JSON.parse(JSON.stringify(dehydrate(queryClient))) but none of them worked.
What can I do?
I stumbled across the same error just today, JSON.stringify(dehydrate(queryClient)) or serializing dehydrate(queryClient) by any means won't really work as the object your completeGoogleAuth function is returning has function values in the key-value pairs, here's a picture of the config object.
And as you know, functions can't be JSON serialized as straightforwardly. Now, what I assume you used(or what I did too) for the completeGoogleAuth fetcher function is use Axios as your API client library. I have found that Axios returns objects that can't be JSON serialized. As a solution, I have just used the native JavaScript fetch() API to get API data and the haven't faced any issues since then.
Here's my fetcher function:
export const getScholarshipInfoSSR = async (token) => {
const response = await fetch(
process.env.NEXT_PUBLIC_API_BASE_URL + portalRoutes.getScholarshipInfo,
{
headers: { Authorization: `JWT ${token}` },
}
);
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json().then((data) => ({ data }));
};
Here's the prefetched useQuery invocation:
await queryClient.prefetchQuery("portal", () =>
getScholarshipInfoSSR(token)
);

Ionic read local JSON file

I am trying to read a local JSON file in Ionic 3. I have saved the JSON file in assets folder as csvjson.json
I call the following function inside one of the services.
getProducts() {
console.log('Inside getProducts')
return this.http.get(this.apiHost)
.map((response: Response) => {
console.log(response);
return response.json();
});
}
and then store the result in
myArray = this.databaseprovider.getProducts();
console.log("Returned from getProducts:" + myArray.length);
However I get the output as
Returned from getProducts:undefined
Can you pls suggest where I am going wrong?
Put the <file-name>.json file in assets folder and change the request to following,
public getProducts() {
return new Promise((resolve, reject) => {
this._http.get("assets/<file-name>.json")
.map((response: Response) => {
console.log(response);
resolve(response.json());
});
});
}
Component file
this.databaseprovider.getProducts().then((result)=>{
myArray = result;
});
console.log("Returned from getProducts:" + myArray.length);
The easiest way is to use fetch() function like that:
readJsonData(){
fetch("../../assets/data/Parameters.json").then(res=>res.json()).then(json=>{
console.log("OUTPUT: ", json);
//DO YOUR STAFF
});
}```
When you call it in your Typescript File of your Page for example called yourPage.ts in the yourPage folder you can access the local JSON File by importing it:
yourPage.ts:
import * as JSONdata from "../../assets/csvjson.json" //You can name 'JSONdata' as you want
To call it:
getProducts() {
console.log(JSONdata);
}
import { HttpClient } from '#angular/common/http';
constructor(private http: HttpClient) { }
this.http.get("assets.data.json").subscribe((data:any)=>{
console.log(data);
});

how to fetch data from json in angular 4

Hi everyone plz help me I have Json string which is I am getting from Node api .I want only single value from that string.
I have service.ts from which I am calling api and subscribe the data on my component file .
Json string is [{"_id":5,"name":"ram,shyam,kamal,kishore"}]
I want only name value. how to achieve this.
service.ts code is given below
empservicecall() {
return this.http.get("http://localhost:3000/api/Employee")
}
component.ts code is given below
GetEmpName(){
this.Emp.empservicecall()
.subscribe(
response =>{
this.name=response.json})
}
it is not working and also error is coming in this code at line response.json().
plz help me
The solution to your issue completely depends on which version of Angular you are on and whether you're using Http or HttpClient.
If you're using HttpClient, then:
empservicecall() {
return this.http.get("http://localhost:3000/api/Employee");
}
And in your Component:
GetEmpName(){
this.Emp.empservicecall()
.subscribe(response => {
console.log(response);
this.name = response[0].name
});
}
If you're using Http(which has been deprecated after the introduction of HttpClient in Angular 4.3 BTW), then:
import 'rxjs/add/operator/map';
empservicecall() {
return this.http.get("http://localhost:3000/api/Employee")
.map((res: any) => res.json());
}
And in your Component:
GetEmpName(){
this.Emp.empservicecall()
.subscribe(response => {
console.log(response);
this.name = response[0].name
});
}

HTTP Native Plugin (IONIC 3)

I'm trying to make a post request using the HTTP cordova plugin. However, for some reason, the JSON data consumed by the Server side is not being formatted correctly (json brakets). Could anyone help me please?
The import:
import { HTTP } from '#ionic-native/http';
The request implementation:
public sendData(sufix, json) {
return new Promise((resolve, reject) => {
this.http.post(URL+sufix, JSON.stringify(json), {'Content-Type': 'application/json'}).then(result => {
resolve(result.data);
}).catch(error => {
reject(error);
});
});
}
The json sended:
{name: 'Test'}
The content received by the server:
=%7B%22name%22%3A%22Test%22%7D
The server implementation:
#Path("/register")
public class RegisterEndPoint {
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response registerUser(UserDTO userDTO) {
// Create DAO for persistence
FactoryDAO factory = new FactoryDAO();
UserDAO userDAO = factory.getUserDAO();
// Create user to be persisted
if (!userDAO.userExist(userDTO.getEmail())) {
User user = new User();
user.setPassword(userDTO.getPassword());
user.setEmail(userDTO.getEmail());
user.setName(userDTO.getName());
userDAO.persist(user);
userDAO.commit();
return Response.status(200).build();
}
return Response.status(405).entity(new ErrorDTO("User already registered!")).build();
}
}
The problem seems to be in Native Plugin, so I've changed to the angular http solution, and it works fine. Follow below the solution which I've perform. Thanks everyone who helped me.
The imports required:
import { Http, Headers, RequestOptions, Response } from '#angular/http';
import { Observable } from 'rxjs/Rx'
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/timeout';
AuthProvider:
public sendRequest(sufix, json) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(URL+sufix, json, options)
.timeout(TIMEOUT_REQUEST*1000)
.do(this.logResponse)
.map(this.extractData)
.catch(this.handleError)
}
private logResponse(res: Response) {
console.log(res);
}
private extractData(res: Response) {
return res.json();
}
private handleError(res: Response | any) {
return Observable.throw(res.json().error || 'Fail to connect to the server');
}
Calling the AuthProvider:
this.authProvider.sendRequest('register', this.signup).subscribe((data) => {
console.log('Success!');
}, (error) => {
console.log(error);
});
Providers included in app.module.ts
import { HttpModule, JsonpModule } from '#angular/http';
can you please try sending the body without making it a string. you can send the JSON Object without stringify. Give it a try :)
**UPDATE
After sending this
{name: 'Test'}
If you are getting name = "test"
Why dont you try like this
var data = JSON.stringify(data);
var obj = {data:data};
//send the obj Object
So it will show as data = "{name:test}"
Now Parse it from the server. Try and let me know :)
if you are trying to make post request using HTTP then try sending request in this format.
let body = new FormData();
body.append('name', 'Test');
this.http.post(<url>,body);
Try and lemme know if it works for you.
Just add this.http.setDataSerializer(‘json’) before do the post

Ionic2 and get Json

I am trying to use Ionic2 and I made a service to fetch a local stored Json.
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
#Injectable()
export class Page1Service {
public constructor(private _http: Http) {}
public GetItems() {
return this._http.get('/app/Ressources/Items.json').map((response: Response) => response.json().data);
}
public PrintJson():boolean {
var myresult;
this.GetItems().subscribe((result) => {
myresult = result;
console.log(result);
});
}
I also a made PrintJson() method that just print the json for test purpose.I got the error:
GET http://localhost:8100/app/Ressources/slides.json 404 (Not Found)
I don't get why. And I can't find an easy and uptodate tutorial. Or should I use fetch()?
First copy your json to the following dir(you can create the folder "data"):
[appname]/www/data/data.json
Type in the following command in your console:
ionic g provider JsonData
It should create a provider for you.Go to that page and enter the following in load() function:
load() {
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object.
// Next we process the data and resolve the promise with the new data.
this.http.get('data/data.json').subscribe(res => {
// we've got back the raw data, now generate the core schedule data
// and save the data for later reference
this.data = res.json();
resolve(this.data);
console.log(this.data);
});
});
}
I usually create an Observable wrapped around the api-call like this:
public GetItems() {
return Observable.create(observer => {
this._http.get('/app/Ressources/Items.json').map(res =>res.json()).subscribe(data=>{
observer.next(data)
observer.complete();
});
});
}
Then I have to subscribe on that method in order to get the results and do something with it. (You could be to delegate the result to a list in the GUI)
GetItems().subscribe(data=>{
myResult = data;
});
EDIT: It might help to put this in the class as well
export class MyClass{
static get parameters(){
return [[Http]];
}
}
Just try to get the response.json() rather than response.json().data in GetItems() method
The issue is because of different paths of json files in local browser(computer) and device (android). Create data folder inside the src\assets folder. Move your json file into that.
When we run ionic serve, it will move that folder (with file) into www\assets folder. Then do following things:
Import Platform service of ionic2
import { Platform } from 'ionic-angular';
Inject Platform Service.
constructor(private http: Http, private platform: Platform ) { }
Use Platform Service.
public getItems() {
var url = 'assets/data/Items.json';
if (this.platform.is('cordova') && this.platform.is('android')) {
url = "/android_asset/www/" + url;
}
return this.http.get(url)
.map((res) => {
return res.json()
});
}