JSON.stringify does not stringify nested arrays - json

I am currently in investigation why JSON.stringify() does not properly parse my object. This is my object I am trying to parse into a JSON string:
var data = [{
name: string,
active: bool,
data: [
value: number,
date: string
]
}]
However when calling JSON.stringify() on my object, I get a result similar to this:
/* JSON.stringify(data) */
[{
name: string,
active: bool,
data: [
[Object],
[Object],
...
]
}]
Is there a nuance to JSON.stringify that causes this to happen? I'd be happy to add more details to my question if it helps clarify any more details.

I think your data array should be like this:
var data = [{
name: string,
active: bool,
data: { //Use {} instead of []
value: number,
date: string
}
}]

You can actually use the second argument to JSON.stringify. Two options for this, you can either specify all the prop names you want stringified:
var data = [{
name: string,
active: bool,
data: [
{value: number},
{date: string}
]
}]
JSON.stringify(data, ['name', 'active', 'data', 'value', 'date'])
=> '[{
"name":"string",
"active":"bool",
"data":[
{"value":"number"},
{"date":"string"}
]}
]'
Or use a replacer function with the same result:
JSON.stringify(data, function replacer(key, value) { return value})
=> '[{
"name":"string",
"active":"bool",
"data":[
{"value":"number"},
{"date":"string"}
]}
]'
Original source: https://javascript.info/json

You need to change the value of data into a JSON object instead of a JSON array to make it work.
JSON.stringify() seems to parse it without any issues:
working example:
var o1 = [{
"name":"string",
"active":"bool",
"data":{
"value":"number",
"date":"string"
}
}];
var o2 = [{
"name":"string",
"active":"bool",
"data":[
"value",
"number",
"date",
"string"
]
}];
console.log(JSON.stringify(o1)); // outputs: [{"name":"string","active":"bool","data":{"value":"number","date":"string"}}]
console.log(JSON.stringify(o2)); // outputs: [{"name":"string","active":"bool","data":["value","number","date","string"]}]

Related

How to map an object from JSON file to another object?

Here is my json file
{
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": m,
"data": { "age": 26, "born": "UK" }
},
]
}
This data array could have more entries.
I have to map the values into an interface which looks like:
InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
I am unable to change the interface. So I'm trying to do some pseudo coding.
const list;
list = convertToInterfacePerson = (value): Array<InterfacePerson> => {
return {
id: value.id,
title: if(value.gender === "m")? "Mr" : "Mrs",
firstName: value.firstName,
lastName: value.lastName,
age: value.data.age,
//...
}
}
I think you were trying to use a conversion mapping function called convertToInterfacePerson but you hadn't set it up yet (separately from trying to use it). The code below shows it declared and used within a map Array method call. I believe this resolves the error(s) you were getting.
// Copied in the JSON for demonstration
const sourceJson = {
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": "m",
"data": { "age": 26, "born": "UK" }
},
]
};
// Declared the InterfacePerson interface
interface InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
// Declared the conversion mapping function (optional parameter typing included)
const convertToInterfacePerson = (value: { firstName: string, lastName: string, type: string, id: string, gender: string, data: { age: number, born: string } }): InterfacePerson => {
return {
id: value.id,
// Removed the `if` statement due to ternary conditional
title: ((value.gender === "m") ? "Mr" : "Mrs"),
firstName: value.firstName,
lastName: value.lastName,
// Wrapped the value.data.age in a string conversion
age: String(value.data.age),
location: value.data.born
};
}
// Declared and assigned the list based on the returned array from the mapping function (each element is applied in the `convertToInterfacePerson` function)
const list = sourceJson.data.map(convertToInterfacePerson);
// Show the result of the conversion
console.log(JSON.stringify(list, null, 2));
And for a live example, check out this TypeScript Playground script containing this solution.

JSON response cannot extract variables

Brand new to react-native and typescript!
I'm have a bit of trouble extracting JSON response. I was to extract the response and put it into a class as shown below.
Here is the request code
let notifications: INotification[]
notifications = (await Requests.GET('notification/user/test-user-1', accessToken));
Here is the class
export interface INotification {
id: string;
senderId: string;
receiverId: string;
text: string;
isSeen: boolean;
type: string;
timestamp: string;
}
Here is the Postman response
{
"notifications": [
{
"pk": "user-1",
"sk": "notification1234",
"entity": "notification",
"id": "id number",
"senderId": "test-user-2",
"receiverId": "test-user-1",
"text": "Test notifications",
"isSeen": false,
"type": 2
}
]
}
Here is response from the console
{ notifications:
[ { pk: 'user#test-user-1',
sk: 'notification1234',
entity: 'notification',
id: 'id number',
senderId: 'test-user-2',
receiverId: 'test-user-1',
text: 'Test notifications',
isSeen: false,
type: 2 } ]
}
I want to be able to write out:
console.log("TEXT: ",notifications[0].text )
And get the response of : "Text: Test notifications"
Any help welcome!
the data is in an array you need to pass the array first
console.log("TEXT: ", notifications[0].text);

ImmutableJS: Convert List to indexed Map

This question is about Immutable.js library.
I have a List<T>, where T is {name: string, id: number}. I want to convert it to Map<number, T>, with id of T to the keys. Using standard method toMap gives me a Map with sequential indexes, and there is no way to hook there. And no method like indexBy or other. how to do that?
You can do it with a reducer like this:
function indexBy(iterable, searchKey) {
return iterable.reduce(
(lookup, item) => lookup.set(item.get(searchKey), item),
Immutable.Map()
);
}
var things = Immutable.fromJS([
{id: 'id-1', lol: 'abc'},
{id: 'id-2', lol: 'def'},
{id: 'id-3', lol: 'jkl'}
]);
var thingsLookup = indexBy(things, 'id');
thingsLookup.toJS() === {
"id-1": { "id": "id-1", "lol": "abc" },
"id-2": { "id": "id-2", "lol": "def" },
"id-3": { "id": "id-3", "lol": "jkl" }
};

Root property of a nested JSON or model in sencha

i have a json in the following format:
{
"collection": [
{
"id": 4,
"tickets": {
"collection": [
{
"inner_id": 8,
},
{
"inner_id": 10,
}
],
"count": 2,
"type": "collection"
},
},
{
"id": 5,
"tickets": {
"collection": [
{
"inner_id": 1,
},
{
"inner_id": 2,
}
],
"count": 2,
"type": "collection"
},
},
]
}
For this particular JSON i created the models as:
Ext.define("myProject.model.ABC", {
extend: "Ext.data.Model",
config: {
idProperty: "id",
fields:[
{name: "id", type: "int" },
],
hasMany: [
{
model: "myProject.model.XYZ",
name: "tickets",
associationKey: "tickets",
},
],
}
});
And second store as:
Ext.define("myProject.model.XYZ", {
extend: "Ext.data.Model",
config: {
// idProperty: "id",
fields:[
{name: "inner_id", type: "int" },
],
belongsTo: 'myProject.model.ABC'
}
});
But now i am confused. How do i populate the second store with a root property of collection again.
I know one way is to easily change the json so that there is no collection child inside tickets but i dont want to do that.
Any help would be appreciated. I have simplified the JSON for an easy example.
EDIT:
To be more clear, is there a way i can directly create a model which will read the Collection array inside the tickets object.
EDIT:
Adding the store which populates the model ABC for more understanding
Ext.define("myProject.store.ABCs", {
extend: "Ext.data.Store",
config: {
model: "myProject.model.ABC",
autoLoad: false,
proxy: {
type: "ajax",
url: '', //myURL
reader: {
type: "json",
rootProperty: "collection", // this is the first collection
},
},
}
});
This store loads the ABC model correctly but now i want to load the XYZ model which can load the inner array of collection
belongsTo should be define as follows :
Ext.define('Product', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id', type: 'int' },
{ name: 'category_id', type: 'int' },
{ name: 'name', type: 'string' }
],
associations: [
{ type: 'belongsTo', model: 'Category' }
]
Have you read the doc? They specified the root property.
The name of the property which contains the data items corresponding to the Model(s) for which this Reader is configured. For JSON reader it's a property name (or a dot-separated list of property names if the root is nested). For XML reader it's a CSS selector. For Array reader the root is not applicable since the data is assumed to be a single-level array of arrays.
By default the natural root of the data will be used: the root JSON array, the root XML element, or the array.
The data packet value for this property should be an empty array to clear the data or show no data.
Sometimes the JSON structure is even more complicated. Document databases like CouchDB often provide metadata around each record inside a nested structure like this:
{
"total": 122,
"offset": 0,
"users": [
{
"id": "ed-spencer-1",
"value": 1,
"user": {
"id": 1,
"name": "Ed Spencer",
"email": "ed#sencha.com"
}
}
]
}
In the case above the record data is nested an additional level inside the "users" array as each "user" item has additional metadata surrounding it ('id' and 'value' in this case). To parse data out of each "user" item in the JSON above we need to specify the record configuration like this:
reader: {
type : 'json',
root : 'users',
record: 'user'
}
root as a Function
reader: {
type : 'json',
root : function (obj) {
// I can't reproduce your problem
// so you should check in your console collection.id is right
return obj.collection.id
}
}
// Or, we can use dot notation
reader: {
type : 'json',
root : collection[0].tickets.collection
}
There are two ways to solve this problem. After researching extensively, i found two solutions...
SOLUTION 1:
Instead of making a second model, just create one model and create an array field with type as "auto"
Ext.define("myProject.model.ABC", {
extend: "Ext.data.Model",
config: {
idProperty: "id",
fields:[
{name: "id", type: "int" },
{ name: "tickets", convert: function(value, record) {
if(value.collection instanceof Array) {
return value.collection;
} else {
return [value.collection]; // Convert to an Array
}
return value.collection;
}
}
],
}
});
Now you can refer to an array of tickets from records by:
record.get('tickets')
SOLUTION 2:
Create three model instead of two.
Model 1:
hasOne Association with Tickets
Model 2:
hasMany association with Collection
Model 3:
has all the fields of the innermost array
I can give an example if its not clear enough

How to change name of JSON key?

children: [
{
name:'Basic Ext Layouts',
expanded: false,
children:[
{
name:'Absolute',
id:'absolute',
leaf:true,
},{
...
}]
}]
Is it possible to change children to mydata?
Is it possible to change children to mydata?
Yes. Setup treestore's proxy to use reader with root config set to 'mydata':
var store = Ext.create('Ext.data.TreeStore', {
model: 'MyModel',
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'mydata' // << this is required
}
},
root: {
myData: [
{
name:'Basic Ext Layouts',
Here is working example.
JSON format is merely a String in javascript's point of view. So you could manipulate the JSON string with associated method.
JSON.
// The original
obj = {
children: [
{
name:'Basic Ext Layouts',
expanded: false,
children:[
{
name:'Absolute',
id:'absolute',
leaf:true,
}]
}]
}
// Transfer the object to a JSON string
var jsonstr = JSON.stringify(obj);
// HERE you do the transform
var new_jsonstr = jsonstr.replace('"children"', '"mydata"');
// You probably want to parse the altered string later
var new_obj = JSON.parse(new_jsonstr);