How to ignore a variable in JSON data in Angular TypeScript - json

I am facing a problem while reading a JSON file in angular 7.
below is the format of my JSON data file.
[
{
"attributes": {
"User": "jay"
}
},
{
"attributes": {
"User": "roy"
}
},
{
"attributes":{
"User": "kiya"
}
},
{
"attributes":{
"User": "gini"
}
},
{
"attributes": {
"User": "rock"
}
},
{
"attributes": {
"User": "joy"
}
}
]
here is my component.ts file method in which I am calling service for a JSON file.
this.rest.getUsers().subscribe((data: {}) => {
console.log(data);
this.items = data;
//this.items=data;
});
Here is my service.ts file method.
private extractData(res: Response) {
let body = res;
return body || { };
}
getUsers():Observable<any> {
return this.httpService.get('./assets/usersdetails.json').pipe(
map(this.extractData));
}
Now I want to read only User from the JSON file and I want to filter the word attributes. is there any way to filter this thing from JSON file, so that I can only get the User value. because in my Project this attributes in JSON is creating a problem and I want to ignore or filter this.
because in my application I need to read the JSON as below format.
[
{
"User": "jay"
},
{
"User": "roy"
},
{
"User": "kiya"
},
{
"User": "gini"
},
{
"User": "rock"
},
{
"User": "joy"
}
]
but the data is coming in the format as above mentioned JSON format with attributes
so is there any way to filter the extra attributes thing from the JSON at the time of reading.

You don't show the code for the extractData method, so it is hard to say what isn't working there, but you should be able to accomplish your goals with the following.
return this.httpService
.get('./assets/usersdetails.json')
.pipe(
map(data => data.map(d => d.attributes))
);
If there are other properties on 'attributes' and you really only want the 'user' data, then you could further update the code to:
return this.httpService
.get('./assets/usersdetails.json')
.pipe(
map(data => data.map(d => ({ 'User': d.attributes.User })))
);

Related

In a JSON file I need to access to an attribute name with ':' in it

I'm a react-native noob.
I need to read a link inside a JSON field called 'wp:featuredmedia.href'.
obviusly i can't put the ':' char in the code.
I've tried in this way... but I've no success :(
componentDidMount(){
const { navigation } = this.props;
const id = navigation.getParam('id', );
//const percorso = 'responseJson.wp:featuredmedia.rendered';
return fetch('https://www.seisnet.it/wp-json/wp/v2/posts/'+id)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
title: String(responseJson.title.rendered),
photos: String(responseJson.wp:featuredmedia),
}, function(){});
})
.catch((error) =>{
console.error(error);
});
}
EDIT 1
this is a section of the json file:
// 20190726085445
// https://www.seisnet.it/wp-json/wp/v2/posts/1967
"_links": {
"self": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/posts/1967"
}
],
"collection": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/posts"
}
],
"about": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/types/post"
}
],
"wp:featuredmedia": [
{
"embeddable": true,
"href": "https://www.seisnet.it/wp-json/wp/v2/media/1971"
}
],
"wp:attachment": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/media?parent=1967"
}
],
}
}
the field i've to read contains a link to another json file.
i've tried: JSONResponse_embedded["wp:featuredmedia"] and JSONResponse["wp:featuredmedia"]. the first give me the error "undefined is not an object" while the second give me nothing in output
Instead of responseJson.wp:featuredmedia, try responseJson["wp:featuredmedia"]
JavaScript object: access variable property by name as string

Angular HttpClient-subscribe select property from data

I'm really sure about, that this question is answered multiple times in here. But I can't find them/don't knwo which terms to search for.
I've got a JSON-file looking like that:
{
"pages": [{
"displayname": "PageA",
"url": "http://google.de",
"icon": "iconZ"
},
{
"displayname": "PageB",
"url": "http://www.pageb.co.uk",
"icon": "iconY"
}
],
"icons": [{
"alias": "iconZ",
"filename": "iconZ.svg"
},
{
"alias": "iconY",
"filename": "iconY.svg"
}
]
}
Now I'm using the HttpClient (here called httpService) to get the data from the file.
this.httpService.get('./assets/pageconfig.json').subscribe(
data => {
this.arrAdress = data as string[];
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
I want to use the content of pages in my ngFor in the Frontend and I want to get an array of the icon-content for use in the Backend. How can I select/split the data by using the properties.
Thanks for your help
Elias
Considering your pageconfig.json is used in both front and backend, and that you just need the "pages" attribute in your angular app, you may get it this way:
this.httpService.get('./assets/pageconfig.json').subscribe(
data => {
this.arrAdress = data.pages;
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
You don't need to cast the data type.
You could also use the rxjs observable map chaining to parse your data and get only what interests you:
import { map } from 'rxjs/operators';
this.httpService.get('./assets/pageconfig.json')
.pipe(map(data => data.pages))
.subscribe(pages=> {
this.arrAdress = pages;
}.catch((err: HttpErrorResponse) => {
console.log(err.message);
});
I hope this is what you were looking for.
Need to remove string[], instead use Array of object or any.
this.httpService.get('./assets/pageconfig.json').subscribe(
data => {
this.arrAdress = data;
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
sendData(icon){
const matched = this.arrAdress.icons.filter(iconObj => iconObj.alias === icon);
console.log(matched);
}
**Template:**
<div *ngFor="let adress of arrAdress?.pages;" (click)="sendData(adress.icon)">
<span>{{adress.displayname}}</span>
</div>
You have two solutions here to solve this issue
Suppose httpClient.Delete() option returns back you an observable object with employeeId as property in it.
Solution 1 (example)
Create an local variable and assign data to it using let statement (e.g. let response: any = data;).
delete(employee: any) {
this.employeeService.deleteEmployee(employee.id)
.subscribe(
data => {
let response: any = data;
// now you can use response.employeeId
},
(error) => {
console.log(error)
},
() => {
console.log("The operation has been completed")
}
);
}
Solution 2 (example)
Assign type any (e.g. (data : any) to received response
delete(employee: any) {
this.employeeService.deleteEmployee(employee.id)
.subscribe(
(data: any) => {
// now you can use data.employeeId
},
(error) => {
console.log(error)
},
() => {
console.log("The operation has been completed")
}
);
}

Stuck to figure out how to access a certain field to update

I have this JSON FILE
{
"_id": "GgCRguT8Ky8e4zxqF",
"services": {
"emails": [
{
"address": "Abunae#naa.com",
"verified": false,
"verifiedMail": "Toto#hotmail.com"
}
],
"profile": {
"name": "Janis"
},
"pushIds": []
}
I want to update my verifiedMail field but couldn't figure out how to do it in Meteor, it's always returning me an error
let VerifiedEmail = "Exemple1"
await Meteor.users.update({ _id: user._id }, { $set: { 'emails.verifiedEmail': emailRefactor} }, { upsert: true })
Couldn't figure out how to access the emails.verifiedEmail field
Tried this exemlpe worked like a charm
let VerifiedEmail = "Exemple1"
await Meteor.users.update({ _id: user._id }, { $set: { 'profile.name': emailRefactor} }, { upsert: true })
but couldn't figure out how to access emails.verifiedEmail .
Could you please help me ?
Emails is an array, while profile is an object. You have to access the first object of the email array instead
This updates the exact email address from emails
Meteor.users.update({
"emails.address": emailRefactor
}, {
$set: {
"emails.$.verified": true
}
});
Or update the first element
Meteor.users.update({
_id: user._id,
"emails.address": emailRefactor
}, {
$set: {
"emails.0.verified": true
}
});
You're trying to set verifiedEmail while the actual field is verifiedMail.

how can i get string json in angular2

in my angular2 component
keyword_test={};
getData() {
this.service.getData()
.subscribe(
data => {
this.keyword_test = data
console.log(data);
console.log(this.keyword_test);
});
}
console.log(data) and console.log(this.keyword_test) print right data like this
{
"caption": "folder0",
"type": "folder",
"subnodes": [
{
"caption": "folder1",
"type": "folder",
"subnodes": [
{
"caption": "keyword1",
"type": "keyword",
"search_filter_expression": "sfe1"
},
{
"caption": "keyword2",
"type": "keyword",
"search_filter_expression": "sfe2"
}
]
},
{
"caption": "folder2",
"type": "folder",
"subnodes": [
{
"caption": "keyword3",
"type": "keyword",
"search_filter_expression": "sfe3"
},
{
"caption": "keyword4",
"type": "keyword",
"search_filter_expression": "sfe4"
}
]
}
]
}
but in my ngOnInit
ngOnInit() {
this.getData();
console.log(this.keyword_test);
}
despite the this.getdata(), this.keyword_test print "Object {}" i think none object.
Is the keyword_test initialized incorrectly?
when i print console.log(typeof data) in getData function, result is string...
I did change it to json in service, but I do not know why.
++and this is my service
#Injectable()
export class keywordService {
private API_URI: string = 'MYAPIURL';
constructor(private http: Http) {
}
getData() {
return this.http.get(this.API_URI, {body: ""})
.map(res => {res.json();
});
}
}
ngOnInit() {
this.getData(); // this execute but data arrives with call back
console.log(this.keyword_test); //this execute before data has arrived and thats why it is not printing the result from success call
}
Correct way
this.service.getData()
.subscribe(
data => {
this.keyword_test = data
console.log(data);
console.log(this.keyword_test);
});

Elasticsearch: how can i create mapping before upload json data into Elasticsearch

I'm trying to create mapping before uploading json data into elasticsearch.
I don't know how to implement mapping before uploading json data in sails.js
This is my bulkupload snippet
var body = [];
//row is json data
rows.forEach(function(row, id) {
body.push({ index: { _index: 'testindex', _type: 'testtype', _id: (id+1) } });
body.push(row);
})
client.bulk({
body: body
}, function (err, resp) {
if (err)
{
console.log(err);
return;
}
else
{
console.log("All Is Well");
}
});
I want to create mapping before data upload.can any one know how to create mapping in sails.
my Json object
[ { Name: 'paranthn', Age: '43', Address: 'trichy' },
{ Name: 'Arthick', Age: '23', Address: 'trichy' },
{ Name: 'vel', Age: '24', Address: 'trichy' } ]
Before making your client.bulk() call you first need to make another client.indices.putMapping() call like this in order to save the correct mapping for the data you're about to send via the bulk call:
client.indices.putMapping({
"index": "testindex",
"type": "testtype",
"body": {
"testtype": {
"properties": {
"your_int_field": {
"type": "integer"
},
"your_string_field": {
"type": "string"
},
"your_double_field": {
"type": "double"
},
// your other fields
}
}
}
}, function (err, response) {
// from this point on, if you don't get any error, you may call bulk.
});
Remember that all these calls are asynchronous, so be careful to only call bulk once putMapping has returned successfully.
Sounds like you need PutMapping.