@Jaromanda X is correct- you are looking for JSON.parse. Something like this would suffice:
responseArray = "[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]"
<Item[]> JSON.parse(responseArray)
Obviously, this doesn't do any validation of the response (which is bad practice). You should ideally perform some validation of the result:
responseArray = "[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]"
var result;
try {
itemListResponse = <Item[]>JSON.parse(responseArray);
if(!itemListResponse.has("id") ||
!itemListResponse.has("type") ||
!itemListResponse.has("state")){
throw "Invalid Item";
}
} catch (e){
}
Or, alternatively, use a JSON Schema validator like ajv.
Answer from Derek Brown on Stack OverflowConvert JSON file to Typescript Array of Objects
The interface has an iD field and the json has a date field. They need to be the same types. You also might need to use JSON.parse(stringValue) depending on how you are getting the JSON data.
More on reddit.comangular - Parse array of JSON objects to array of TypeScript objects - Stack Overflow
Parsing JSON array in typescript
angular - How to parse an array of json object to typescript (object) after a get method - Stack Overflow
I am reading in a JSON file and attempting to convert them to an array of objects. I get a syntax error on the component file.
This is the component code:
import * as blogs from '../story/stories.json';
import { IStory } from '../models/story';
@Component({
selector: 'app-story',
templateUrl: './story.component.html',
styleUrls: ['./story.component.scss']
})
export class StoryComponent implements OnInit {
stories: IStory[] ;
constructor() { }
ngOnInit() {
this.stories = blogs; <-- syntax error on this line
}this is the story.ts file:
export interface IStory {
id: number;
author: string;
title: string;
pictureUrl: string;
body: string;
}This is the json file, stories.json
[
{"date":3,"author":"AVC", "pictureUrl":"Scorching", "title":"Scorching", "body":"Scorching"},
{"date":4,"author":"ADF", "pictureUrl":"Scorching", "title":"Scorching", "body":"Scorching"}
]The interface has an iD field and the json has a date field. They need to be the same types. You also might need to use JSON.parse(stringValue) depending on how you are getting the JSON data.
It might be simpler to just use the http client to get the json. Pass it the type and you should get proper data objects back.
I think it's because of your mapping in your product class and also the type of your class, try to change class Product to interface Product
like this
export interface Product{
public id: number;
public name: string;
public category: string;
public price: number;
public description: string;
public currencyCode: string;
}
you can go take a look at Angular : Class and Interface for the differences between class and interface
EDIT : (as you can see in my code, I also changed the variable name to match with your JSON response)
Another approach could be to make JSON data, compatible with your Product class. You could use the map rxjs operator to transform your JSON data into Product. Modify the get products code, like this
const source$ = of(result).pipe(pluck('result'),map(item=> item.map(x=>{
let product = new Product(x.id,x.name, x.category, x.price, x.description, x.currencyCode);
return product;
})));
Here is a StackBlitz link.
There are several problems with your code.
Firstly the json syntax mandates you quote the properties do "val1": "test1" not val1: "test1".
Secondly you should use the import fs = require('fs') syntax for the import.
Thirdly and most importantly, you write the json, as a string to the file. The jsonString is already a string, no need to use stringify on it again. If you do the result of parse will be a string not an object array.
interface MyObj {
val1: string
val2: string
val3: string
}
import fs = require('fs')
const file = 'test.json'
const encode = 'utf8'
const jsonString = '[{"val1" : "test1", "val2" : "test2", "val3" : "test3"}, { "val1" : "test4", "val2" : "test5", "val3" : "test3"}]'
fs.writeFileSync(file, jsonString);
fs.readFile(file, encode, (err, data) => {
const objs = JSON.parse(data) as MyObj[]
console.log(data)
console.log(objs)
for (const obj of objs) {
console.log(obj)
console.log(obj.val1)
console.log(obj.val2)
console.log(obj.val3)
}
})
The problem is that you don't have any double quotes (") around the keys in your objects. Therefore the JSON is not valid and the browser can not parse it successfully.
So instead of
{
val1: "test1",
val2: "test2",
val3: "test3"
}
you should have
{
"val1": "test1",
"val2": "test2",
"val3": "test3"
}
You can always check that you have valid JSON on websites like jsonlint.com.
First of all, I assume the data that you passed into convertData function is not an array.
Only Array or Observable have map function in this case.
Also, chained function has been changed into pipeable operators in RxJS 6
https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md
Secondly, looking at the error message - I don't think the data value returned from the endpoint has value.
Third, data.map(item => {this.serializer.fromJson(item)}); - if the arrow function inside the map function is wrapped in curly bracket, you need to have return keyword.
in other word, data.map(item => {this.serializer.fromJson(item)}); should be data.map(item => this.serializer.fromJson(item)); or data.map(item => {return this.serializer.fromJson(item)});
Use subscribe instead of map to return the response.
return this.httpClient
.put<T>(`${this.url}/${this.endpoint}`, JSON.stringify(item), {
headers: this.addHeaders()
})
.subscribe(data => this.serializer.fromJson(data) as T);
BTW RXJs6 has changed the implementation of using observable map function
So, what you want to do is to map all the values in the array using <Array>.map. Then you can return the object as an Array in 2 ways, first is using <Object>.values or by just doing [obj.firstName, obj.lastName, obj.age]
You could try Looping through the array and change the values as well using a for loop, but that it really verbose. I'd recommend the 1st approach, since that's more dynamic in this case.
So the resulting code will be
let data = [
{
"firstName": "Rajesh",
"lastName": "Kumar",
"age": "25"
},
{
"firstName": "john",
"lastName": "david",
"age": "26"
}
];
// I'm assigning the value to the variable called data in this case
data = data.map(item => Object.values(item));
// Now the value of data is the array you want it to be
Now you can follow the other approaches as I specified, however this is the least verbose way to go around.
This will give you what you are looking for
const array = [
{
"firstName": "Rajesh",
"lastName": "Kumar",
"age": "25"
},
{
"firstName": "john",
"lastName": "david",
"age": "26"
}
];
// Under result you will have the required array
const result = a.map(x => [Object.keys(x).map(key => x[key])])
// Or, explicit
const result = array.map(x => [x.firstName,x.lastName,x.age])
There are several problems with your code.
Firstly the json syntax mandates you quote the properties do "val1": "test1" not val1: "test1".
Secondly you should use the import fs = require('fs') syntax for the import.
Thirdly and most importantly, you write the json, as a string to the file. The jsonString is already a string, no need to use stringify on it again. If you do the result of parse will be a string not an object array.
interface MyObj {
val1: string
val2: string
val3: string
}
import fs = require('fs')
const file = 'test.json'
const encode = 'utf8'
const jsonString = '[{"val1" : "test1", "val2" : "test2", "val3" : "test3"}, { "val1" : "test4", "val2" : "test5", "val3" : "test3"}]'
fs.writeFileSync(file, jsonString);
fs.readFile(file, encode, (err, data) => {
const objs = JSON.parse(data) as MyObj[]
console.log(data)
console.log(objs)
for (const obj of objs) {
console.log(obj)
console.log(obj.val1)
console.log(obj.val2)
console.log(obj.val3)
}
})
The problem is that you don't have any double quotes (") around the keys in your objects. Therefore the JSON is not valid and the browser can not parse it successfully.
So instead of
{
val1: "test1",
val2: "test2",
val3: "test3"
}
you should have
{
"val1": "test1",
"val2": "test2",
"val3": "test3"
}
You can always check that you have valid JSON on websites like jsonlint.com.