Saving data from JSON to object - json

I have a problem with pushing data from json to object.
This solution works for me but I am not happy with it. Look at the service.
Is there better way to save data from this json to object?
The json that i get from server looks like this:
{"documents": {"document": [
{
"id": 1,
"description": "Lorem ipsum",
"date": "2017-03-01"
},{
"id": 2,
"description": "Lorem ipsum",
"date": "2017-04-01"
}
]}}
My service:
downloadDocuments(id: number): Observable<DocumentsDTO[]>{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', this.authorizationService.basic);
let options = new RequestOptions({headers: headers});
let body = JSON.stringify(id);
return this.http
.post(DOCUMENTS_URL, body, options)
.map((response) => response.json().documents.document)
}
And component where I call this service:
documentsArray: Array<DocumentsDTO>;
downloadUserDocuments(id: number) {
this.documentsService.downloadDocuments(id)
.subscribe(documents =>{
if(documents !=null){
this.documentsArray = [];
documents.forEach((data) => {
this.documentsArray.push(data);
});
}
});
}
This solution works for me but I am not happy with .
Is there better way to save data from this json to array?

Service
return this.http
.post(DOCUMENTS_URL, body, options)
.map((res: Response) => {
res.json().map((obj) => {
new Document(obj.id, obj.description, obj.date)
})
})
This should return a collection of Documents

I'm not seeing how you could get past
.map((response) => response.json().documents.document)
This is just where your array is placed inside the response, period. You'd have to make changes to backend to change this.
What I am not understanding is why you are doing unnecessary iteration inside your subscribe, why not directly assign the array that is coming to your documentsArray? Like so:
this.documentsService.downloadDocuments(id)
.subscribe(documents => {
if(documents != null) {
this.documentsArray = documents;
}
});

Related

Access String array in Json

The API I am using has a nested string array it seems, I need to extract the path from it, but I cannot figure out how....
This is a break down of what I need to access.
the productimage is wrapped in quotes...
[
{title: "Item 1",
productimage: "[{"1":{"size":"75x75","path":"/10000/img.jpg"}]"
},
{title: "Item 2",
productimage: "[{"1":{"size":"75x75","path":"/20000/img.jpg"}]"
}
]
I am trying to access the image path...
The problem seems to be reading the string, I have attempted to treat it like an array, and a string and get mixed results..
Edited:
here is the entire productimages object, it is coming from an apache database that i have no control over.
productimages: "[{"1":{"size":"75x75","path":"/100000/101819-75x75-A.jpg"}},{"2":{"size":"222x222","path":"/100000/101819-600x600-A.jpg"}},{"3":{"size":"328x328","path":"/100000/101819-600x600-A.jpg"}}]"
my current axios call looks like this.
async function handleSubmit(searchData) {
if (searchData) {
const payload = searchData;
try {
const response = await axios({
url: `${baseUrl}q=*:*&fq=title:${payload}&fq=storeid:1234
method: "get",
});
//Set Hook
setData(response.data.response.docs);
} catch (error) {
console.error(error);
}
}
}
Here is the response data that is being set..
{productid: 1234, itemups: 1234, title: "productname", productimages: "[{"1":{"size":"75x75","path":"/100000/101819-75x75-A.jpg"}},{"2":{"size":"222x222","path":"/100000/101819-600x600-A.jpg"}},{"3":{"size":"328x328","path":"/100000/101819-600x600-A.jpg"}}]", productcount: 7}
I can get everything out of this, except the image.
You've to parse productimage:
const parsedArray = array.map(obj => {
let path = '';
try {
const productimage = JSON.parse(`${obj.productimage}`);
path = productimage[0].path
} catch(err) {
console.error(err)
}
return { ...obj, path }
});
[EDIT]
Axios response:
axios() // some axios call
.then(res => res.data)
.then(array => {
// ... here you can transform your array
})
Also make sure your json is properly formatted.
{
[
{"title": "Item 1",
"productimage": "[{"1":{"size":"75x75","path":"/10000/img.jpg"}]"
]
}

Angular Js parse deeper JSON file

I am trying to parse an array inside an object. I tried to map the result to get the array but could not reach to the point of the array.
My JSON looks like this.
{
"id": 1,
"projectName": "Opera house",
"projectDescription": "This image was taken during my first photography course.",
"thumbnailImageName": "1.JPG",
"projectDetails": {
"id": 1,
"relatedPhotos": [
"1.JPG",
"2.JPG",
"3.JPG"
],
"location": "Sydney",
"scope": "Learn basic of photography",
"description": "Some description"
},
"favouriteProject": true
}
And I am mapping the HTTP response from a server like this.
this.projectService.getProjectDetailsByProjectName(projectName).subscribe(res =>
{
Object.keys(res).map(key => {
this.projectDetails = res[key];
})
});
The above mapping gives me the projectDetails object but cannot access the array inside it. While accessing the array, I get output three times. Two times undefined and finally the actual value. Can anyone guide me how to parse the above JSON file properly?
Thank you very much..
************Edited code****************
My code to get the http response and parse each object is as follows:
getSelectedProjectWithDetails(){
const projectName:string = this.activatedRoute.snapshot.paramMap.get("project-name");
this.projectService.getProjectDetailsByProjectName(projectName).subscribe(res => {
// console.log(res.relatedPhotos);
Object.keys(res).map( (key, value) => {
this.projectDetails = res[key];
console.log(this.projectDetails["relatedPhotos"])
})
})
}
I have project interface as
export interface project{
id:number;
projectName: string;
projectDescription: string;
favouriteProject: boolean;
thumbnailImageName: string;
projectDetail: projectDetail;
}
and projectDetails interface as:
export interface projectDetail{
id: number;
relatedPhotos: String [];
location: string;
scope: string;
description: string;
}
and http get request is
getProjectDetailsByProjectName(projectName: String): Observable<project>{
return this.http.get<project>("http://127.0.0.1:8080/project/"+projectName);
}
As an alternate you can user JSON.parse(res); after you have mapped your response from observable.
like this
Object.keys(res).map(key => {
JSON.parse(res);
this.projectDetails = res[key];
})
However I am using res.json();
addNewProduct(data: any): Observable<string> {
return this._http.post(this.addNewProdUrl, data).map(res => res.json());
}
Not sure what is the issue with your res.
You can use map() to transform HttpResponse body to JSON using json() method. Since response contains body, headers etc. json() can be used to only parse body.
Please look into below code to understand the same.
this.http.get('https://api.github.com/users')
.map(response => response.json())
.subscribe(data => console.log(data));
To know more, please refer documentation

Projecting into subobject when retrieving observable (typescript/angular)

I have some example json coming from an API into an Angular service, a collection of objects like so:
{
"data": {
"id": 1,
"title": "one"
},
"stats" : {
"voteCount": 8
}
}
The 'data' part is what I'd like to submit back in a reactive form in angular, so I'd really like my observable to be a collection of objects with just the id and title:
export class SimpleIssue {
id: number;
title: string;
}
In my angular service I get the data like so:
getItems(): Observable<SimpleIssue[]> {
return this.http.get(this.apiUrl + 'simpleissues/')
.map((response: Response) => <SimpleIssue[]> response.json())
.do(thedata => console.log('all: ' + JSON.stringify(thedata)))
.catch(this.handleError);
}
I would have thought if I'd changed response.json() to response.json().data that might work, or if I added another .map after that line something like:
.map(blah => blah.data)
But no luck. Incidentally, if I bring this in as an 'any' type, I can put {{ myItem.data | json }} and get back exactly what I'd expect, as it's dealing with each collection object.
Can I get this working, or am I missing a fundamental concept of sending different viewmodels for each view, etc?
Thanks
Haven't tested but this should works for your case:
getItems(): Observable<SimpleIssue[]> {
return this.http.get(this.apiUrl + 'simpleissues/')
.map((response: Response) => <any[]> response.json())
.map((arr: any[]) => arr.map(i => i.data))
.do(thedata => console.log('all: ' + JSON.stringify(thedata)))
.catch(this.handleError);
}

Can I return raw json response in angular2

Is it possible for angular2 to return raw json response? Ex.
Component
getrawJson(){
this.someservice.searchJson()
.subscribe( somelist => this.somelist = somelist,
error => this.errorMsg = <any>error);
}
For service
searchJson(num: number, somestring: string, somestring2: string): Observable<stringDataObj> {
let body = JSON.stringify({"someJsonData"[{num, somestring, somestring2}]});
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(URL, body, options)
.map(this.jsonObj)
.catch(this.handleError);
}
private jsonObj(res: Response) {
let body;
return body{ };
}
The above implementation returns Array . Will there be a way for me to get the raw json data returned by the service? I'm expecting to have json response like below
{
"dataParam": [ {
"num": "08",
"somestring": "2016-10-03",
"somestring2": "2016-10-03"
}],
"someDatalist": [ {
"one": "08",
"two": 1,
"three": "2016-10-03"
}]
}
Thanks!
Yes off course you can !!
Actually angualar2 returns Response in the form of Observable instead of promise Like in angular1.x , so in order to convert that observable into raw Json format we have to use the default method of angular2 i.e
res.json()
There are no of method apart from .json() provided by angular which can be described here for more info.
methods include
res.text()
res.status
res.statusText
etc
https://angular.io/docs/ts/latest/api/http/index/Response-class.html
update
use your code like this
return this.http.post(URL, body, options)
.map(res => {return res.json()})
.catch(this.handleError);
}
private jsonObj(res: Response) {
return res.json() || {} ;
}

Accessing JSON object properties directly and log it

I'm trying to access JSON Object properties directly and log it, here is my function :
loadProcesses(filter?){
this._postService.getAllProcess(filter)
.subscribe(
res=> {
this.processListe = res;
// console.log(this.processListe.)
}
,null,
() =>{
console.log("get processes liste" + filter)
});
So this.processListe contain a JSON Object, and my JSON format is like this:
{"Person": {
"id": "A256",
"name": "GET",
"status": "active",
"description": "hardworking, openminded",
...
So it will contains exactly the same things, for example if i want to simply print the label on a console log how can i do it ??
Are you looking for something like this:
function parseObject(obj)
{
for(var key in obj)
{
console.log("key: " + key + ", value: " + obj[key])
if(obj[key] instanceof Object)
{
parseObject(obj[key]);
}
}
}
just call parseObject(res) in the subscribe method.
parse it and access the fields.
var obj = JSON.parse(filter);
obj.Person.id;
//etc
parse it in the .subscribe:
res => this.processListe = res.json();
a better solution is to declare your response with any :
loadProcesses(filter?){
this._postService.getAllProcess(filter)
.subscribe(
(res: any)=> {
this.processListe = res;
// console.log(this.processListe.)
}
,null,
() =>{
console.log("get processes liste" + filter)
});
this way you can access any attirbute in your response