@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 OverflowAs you asked, here's how to do it:
- Mapping the array to an object
- Converting the object to JSON
let array = [{
Field: 'Key',
Value: '7'
},
{
Field: 'City',
Value: 'Some City'
},
{
Field: 'Description',
Value: 'Some Description'
}
];
// #1 Mapping the array to an object...
let obj = {};
array.forEach(item => obj[item.Field] = item.Value);
// #2 Converting the object to JSON...
let json = JSON.stringify(obj);
console.log(json);
Bonus (ES6 + reduce):
const obj = array.reduce((acc, { Field, Value }) => ({ ...acc, [Field]: Value }), {});
you can try the below approach . I have used spread operator(ES6) and Object.assign to create the object ,then converted it into json string.
let SampleData = [
{ Field: 'Key', Value: '7'},
{ Field: 'City', Value: 'Some City'},
{ Field: 'Description', Value: 'Some Description'}
];
let obj = Object.assign(...SampleData.map( x => Object.values(x)).map(y => ({[y[0]]: y[1]})));
console.log(obj);
//{ Key: "7", City: "Some City", Description: "Some Description" }
console.log(JSON.stringify(obj));
Videos
To convert any JSON to array, use the below code:
const usersJson: any[] = Array.of(res.json());
That's correct, your response is an object with fields:
{
"page": 1,
"results": [ ... ]
}
So you in fact want to iterate the results field only:
this.data = res.json()['results'];
... or even easier:
this.data = res.json().results;
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.
If the response is what you included then it's simple:
JSON.parse(data.text()).forEach(item => {
console.log(item.name);
});
As your body is an array of objects of this interface:
interface ObjectInResponseArray {
name: string;
}
First off, you're mixing up JSON and objects. JSON is a text format for transferring data. Once you parse it (JSON.parse) you've got an object or an array, depending on the contents of the JSON.
var json = "{\"key\": \"value\" }";
var object = JSON.parse(json);
json = "[1, 2, \"three\"]";
var array = JSON.parse(json);
Next, it looks like you already have an object. If you do JSON.stringify, you're converting an object into a string. So you can access your data object directly. No need to convert one way or the other.
console.log(data._body[0]);
Are you familiar with for loops? They're the most common way of iterating through an array in JavaScript (and most languages, actually). For example:
var objs = [
{
name: 'Bugs'
},
{
name: 'Bunny'
}
];
for (var i = 0; i < objs.length; i++) {
var obj = objs[i];
console.log(obj.name);
}
Given all of that, you should be able to iterate over your data._body array and access the name property on each element.
Since your question is a bit unclear, it's possible you'll need to iterate over the parsed contents of data.text().
var objs = JSON.parse(data.text());
// Use a simple loop like above
It would be like the following (assuming response.data is where the JSON text is).
const items: Array<{title: string, image: string}> = JSON.parse(response.data)
const sliderObjects = items.map(item =>
new SliderObject(item['title'], item['image']))
You can come up with your own reviver and conventions in your models to support proper deserialization.
class SliderObject {
public title: StringField;
public image: UrlField;
constructor(title: string, image: string) { /* class initialization */ }
static fromJSON(data: { image: string; title: string; }): SliderObject {
return new SliderObject(data.title, data.image);
}
static isDeserializableFromJSON(data: any): data is { image: string; title: string; } {
return data && typeof(data.image) === 'string' && typeof(data.title) === 'string';
}
}
function jsonReviver(_: string, value: unknown): unknown {
if (SliderObject.isDeserializableFromJSON(value)) {
return SliderObject.fromJSON(value);
}
return value;
}
console.log(JSON.parse(`[/* array data */]`, jsonReviver));
In the example above I have added to static methods to SliderObject to help with serialization and a custom json reviver function. The static methods detect if data create from JSON.parse can be used to create a sliderObject and the other actually creates the new class. The reviver will call the guard method and return a SliderObject if the guard passed.
There are lots ways to skin this cat. I personally eschew TypeScript classes in favor of interfaces which I find are more flexible. Why try to make TypeScript C# or Java? By using interfaces, I can largely avoid situations like these.