Reputation: 9833
I'm trying to convert my JSON data into a KeyValue
array so that I can assign it to the options of a p-dropdown
component but for some reason I cannot call JSON.parse()
on the data
key-value.ts
export interface KeyValue {
text: string;
value: string;
}
domains.json
{
"Domains": [
{"North America (NAM)": "NAM"},
{"Europe (EUR)": "EUR"},
{"Australia (AUS)": "AUS"},
{"Latin America (LAAM)": "LAAM"},
{"Asia (APA)": "APA"}
]
}
domains.service.ts
getDomains(): any {
return this.getJSON().subscribe(data => {
console.log("JSON data.Domains: " + JSON.stringify(data.Domains)); //See >> output
let sids: KeyValue[] = JSON.parse(data.Domains); // See >> exception
return data.Domains;
});
}
getJSON(): Observable<any> {
return this.http.get("assets/dd.json")
}
>> output
JSON data.Domains: [{"North America (NAM)":"NAM"},{"Europe (EUR)":"EUR"},{"Australia (AUS)":"AUS"},{"Latin America (LAAM)":"LAAM"},{"Asia (APA)":"APA"}]
>> exception
core.js:1449 ERROR SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () at SafeSubscriber.eval [as _next] (utilitynet.service.ts:25) at SafeSubscriber.__tryOrUnsub (Subscriber.js:243) at SafeSubscriber.next (Subscriber.js:190) at Subscriber._next (Subscriber.js:131) at Subscriber.next (Subscriber.js:95) at MapSubscriber._next (map.js:85) at MapSubscriber.Subscriber.next (Subscriber.js:95) at FilterSubscriber._next (filter.js:90) at FilterSubscriber.Subscriber.next (Subscriber.js:95)
Upvotes: 0
Views: 2219
Reputation: 39432
data.Domains
is already a JS Object. So you don't need to call JSON.parse
on it.
Just do
let sids: KeyValue[] = data.Domains;
Also, I'm assuming that getDomains()
is a method that you're going to call from a component and subscribe to it in there only.
So just refactor your code like this:
import { map } from 'rxjs/operators';
...
getDomains(): any {
return this.getJSON().pipe(
map(data => data.Domains)
);
}
...
getJSON(): Observable < any > {
return this.http.get("assets/dd.json")
}
You can then use it in your Component like this:
this.domainsservice.getDomains()
.subscribe(domains => {
console.log(domains);
...
});
Upvotes: 2