angular encode part of $scope to json - json

I'm working with angular and have most of my api functioning, but I'm having trouble with a put function. My server is hosted by an arduino and can't receive all the data sent by the json stringify.
How to make a JSON obj with only certain $scope data?
This is what I've got so far, with 'chanObj'. The alert returns in some tests "undefined", and on other tests an empty object at the end of the scope.
$scope.setpointClk = function(channel, setpoint) {
var channels = JSON.stringify($scope.channels); //original obj to big
var chanObj = {setPoint : channel.setPoint, name : channel.name
}; //try to create a selected content obj
alert(chanObj);
service.putChannels(channels, function() {
$scope.init();
});
}
channels: [{name: null, canal: "0", status: false, temperature: 19.94, setPoint: 0, permission: false,…},…]
0: {name: null, canal: "0", status: false, temperature: 19.94, setPoint: 0, permission: false,…}
1: {name: null, canal: "1", status: false, temperature: 20.37, setPoint: 5, permission: false,…}
2: {name: null, canal: "2", status: false, temperature: 0, setPoint: 5, permission: false, percentOut: 0}
3: {name: null, canal: "3", status: false, temperature: 0, setPoint: 5, permission: false, percentOut: 0}
4: {name: null, canal: "4", status: false, temperature: 19.94, setPoint: 5, permission: false,…}
5: {name: null, canal: "5", status: false, temperature: 19.87, setPoint: 5, permission: false,…}
6: {name: null, canal: "6", status: false, temperature: 19.98, setPoint: 5, permission: false,…}
7: {name: null, canal: "7", status: false, temperature: 19.96, setPoint: 5, permission: false,…}
8: {name: null, canal: "8", status: false, temperature: -50, setPoint: 5, permission: false,…}
9: {name: null, canal: "9", status: false, temperature: -50, setPoint: 5, permission: false,…}

You should create your chanObj without first calling the JSON.stringify function. Because that would convert your $scope.channels into a string.
E.g. on how to create your chanObj with specific properties from your $scope.channels
$scope.setpointClk = function(channel, setpoint) {
...
var chanObj = {
setPoint: $scope.channels.setPoint,
name: $scope.channels.name
};
...
}

Just create a new object and pass that to the put call, like you have with the chanObj object, pass that to the put.
If you have a lot of properties to maintain, you could do something like this:
var propertiesToCopy = ["setPoint", "name", "foo", "bar"],
cutdownVersion = {};
for(var key in propertiesToCopy) {
cutdownVersion[key] = channels[key];
}
Then pass the cutdownVersion object to the put call.

Related

Reading data from object array of arrays in typescript/angular

I'm calling my api which returns me the object array like below.how can I access the array of array object like in below json I want to find out role of roleid =2 when EmpId is 102 using typsecript.
0- {
EmpId: 101,
EmpName:'abc'
Role :
0- {roleid :1,
role:Admin,
isdeletee:true},
1- {roleid :2,
role:user,
isdeletee:true},
2- {roleid :3, role :Admin,
isdeletee:true}
}
1- {
EmpId: 102,
EmpName:'xyz'
Role :
0- {roleid :1,
role:Admin,
isdeletee:true},
1- {roleid :2,
role:user,
isdeletee:true},
2- {roleid :3, role :Admin,
isdeletee:true}
}
2- {
EmpId: 103,
EmpName:'xez'
Role :
0- {roleid :21,
role:userx,
isdeletee:true},
1- {roleid :2,
role:user,
isdeletee:true},
2- {roleid :31, role :ad,
isdeletee:true}
},
Its hard to understand exactly what you want from you question.
Are you looking for something like this? Its just a sample I would add null checks in between in practical use.
const response = [{
EmpId: 101,
EmpName: "abc",
Role: [{
roleid: 1,
role: "Admin",
isdeletee: true
},
{
roleid: 2,
role: "user",
isdeletee: true
},
{
roleid: 3,
role: "Admin",
isdeletee: true
},
],
},
{
EmpId: 102,
EmpName: "xyz",
Role: [{
roleid: 1,
role: "Admin",
isdeletee: true
},
{
roleid: 2,
role: "user",
isdeletee: true
},
{
roleid: 3,
role: "Admin",
isdeletee: true
},
],
},
{
EmpId: 103,
EmpName: "xez",
Role: [{
roleid: 21,
role: "userx",
isdeletee: true
},
{
roleid: 2,
role: "user",
isdeletee: true
},
{
roleid: 31,
role: "ad",
isdeletee: true
},
],
},
];
const role = response
.filter((emp) => emp.EmpId === 102)[0]
.Role
.filter((roles) => roles.roleid === 2)[0]
.role;
console.log(role);

jsondecode loading issue in dart

I try to run below code in flutter App but it loads half JSON data, same API when running for a web app it works fine.
Any idea how to solve this issue?
Example
Future <List> test() async{
final response = await http.post(
"https://xyz/allData",
body: jsonEncode({
"email": "email"
}),
headers: {
HttpHeaders.contentTypeHeader: ContentType.json.toString(),
HttpHeaders.authorizationHeader: token
});
final data= json.decode(response.body);
OR
Map<String, dynamic> data =json.decode(response.body);
Error
half JSON fetch by above code
below content I recieved :
{success: true, msg: Loaded, content:
{total: 3, on: 0, off: 3,
on: {},
off: {
11: {id: 11, last_data: N/A,value: {N/A: {name: N/A, value: N/A}},
name: 01, type: temp, upper: 20, lower: 10, email: [], phn_list: [], id: 01,status: 0, freq: 10, description: 01, status_notf: 0, lat_map: 0, lng_map: 0, html: html},
12: {id: 12, last_data: N/A, value: {N/A: {name: N/A, value: N/A}},
name: 02, type: temp, upper: 20, lower: 10, email: [], phn_list: [], id: 02, status: 0,freq: 10, description: 02, status_notf: 0, lat_map: 0, lng_map

Kendo UI Chart - Visualize count of returned JSON fields

I want to display the counts of specific retrieved fields in my pie/donut chart.
I'm retrieving data via REST and the result is in json format. The source is a list repeating values:
Example: In the following list, I'd like to get a present the number (count) of completed responses; perhaps in a second chart present the breakdown of responses by location.
var userResponse = [
{ User: "Bob Smith", Status: "Completed", Location: "USA" },
{ User: "Jim Smith", Status: "In-Progress", Location: "USA" },
{ User: "Jane Smith", Status: "Completed", Location: "USA" },
{ User: "Bill Smith", Status: "Completed", Location: "Japan" },
{ User: "Kate Smith", Status: "In-Progress", Location: "Japan" },
{ User: "Sam Smith", Status: "In-Progress", Location: "USA" },
]
My Initialization currently looks like this:
$('#targetChart').kendoChart({
dataSource: {
data: data.d.results,
group: {
field: "Location",
},
},
seriesDefaults: {
type: "donut",
},
series: [{
field: 'Id',
categoryField: 'Location',
}],
});
You can easily transform the data. Read it into a DataSource object grouping by location and filtering for completed only. Then fetch the data and create an array of the counts for each location:
var pieData = [];
var respDS = new kendo.data.DataSource({
data: userResponse,
group: {
field: "Location",
},
filter: {
field: "Status",
operator: "eq",
value: "Completed" },
});
respDS.fetch(function(){
var view = respDS.view();
for (var i=0; i<view.length; i++){
var item = {};
item.Location = view[i].value;
item.Count = view[i].items.length;
pieData.push(item);
}
});
You end up with:
[
{Location: "Japan", Count: 1},
{Location: "USA", Count: 2},
]
This can then be bound to a pie/donut.
DEMO

Ember.Data JSON not being pushed into store

I am having trouble getting my API json results to be pushed into the Ember Data object model array. I was previously using getJSON on my route however I now need to be able to filter the data on multiple properties and Ember Data provides built in methods for that...if I could get it work that is. I'm pretty new to this so I am probably missing something terribly obvious. Please let me know if I am missing any code to assist. When I look at the promises, it shows them fulfilled when pulling the data from the API but then it rejects when trying to query the local data store for records (shows null) which I believe means my data isn't getting added to the store in the first place. I would provide a JSBin but our api uses CORS and I can't get the JSbin origin to authenticate.
On the route I have tried the following. Both throw different errors:
return this.store.find('restaurant');
//returns error: Error while processing route: casualdining
//Array.prototype.map: 'this' is null or undefined.
return DineSection.Restaurant.find();
//Error while processing route: casualdining
//Object doesn't support property or method 'find'
The Application Code:
DineSection = Ember.Application.create({
rootElement: "#dinesection-app"
});
DineSection.Router.map(function () {
this.resource("casualdining");
this.resource("restaurant", { path: "/:id" });
});
DineSection.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'https://api.lakecountyfl.gov',
namespace: 'api/TourismListings',
pathForType: function (type) {
return "GetRestaurants";
}
});
DineSection.ApplicationStore = DS.Store.extend({
adapter: 'DineSection.ApplicationAdapter'
});
//SERIALIZE OUR JSON DATA FROM THE API into something ember data can use
DineSection.ApplicationSerializer = DS.RESTSerializer.extend({
normalizePayload: function (type, payload) {
return { restaurant: payload }
}
});
DineSection.Restaurant = DS.Model.extend({
name: DS.attr('string'),
address: DS.attr('string'),
city: DS.attr('string'),
zip: DS.attr('string'),
phone: DS.attr('string'),
website: DS.attr('string'),
facebook: DS.attr('string'),
flickr: DS.attr('string'),
hasphoto: DS.attr('boolean', {defaultValue: false}),
outdoordining: DS.attr('boolean', { defaultValue: false }),
breakfastprice: DS.attr('string'),
lunchprice: DS.attr('string'),
dinnerprice: DS.attr('string'),
description: DS.attr('string'),
primarycategoryname: DS.attr('string'),
primarycategoryslug: DS.attr('string'),
primarysubcategoryname: DS.attr('string'),
primarysubcategoryslug: DS.attr('string'),
foodtype: DS.attr('string'),
foodtypeid: DS.attr('number'),
ranking: DS.attr('number'),
region1: DS.attr('boolean', { defaultValue: false }),
region2: DS.attr('boolean', { defaultValue: false }),
region3: DS.attr('boolean', { defaultValue: false }),
region4: DS.attr('boolean', { defaultValue: false })
});
DineSection.CasualdiningRoute = Ember.Route.extend({
model: function () {
//return Ember.$.getJSON("https://devapi.lakecountyfl.gov/api/TourismListings/GetRestaurants");
return this.store.find('restaurant');
//return DineSection.Restaurant.find();
}
});
My JSON response looks like this (abbreviated to two records for simplicity):
[{
"$id": "1",
"id": 1212,
"name": "Al's Landing",
"address": "111 W. Ruby St.",
"city": "Tavares",
"zip": "32778",
"phone": "352-555-8585",
"website": "http://www.alslanding.com",
"facebook": "https://www.facebook.com/pages/ALS-landing/110275062350544",
"flickr": null,
"hasphoto": true,
"outdoordining": true,
"breakfastprice": "N/A",
"lunchprice": "$10-$20",
"dinnerprice": "$10-$20",
"description": "A casual dining atmosphere with an indoor/ outdoor bar and plenty of outdoor lakefront seating.",
"primarycategoryname": "Dining",
"primarycategoryslug": "dining",
"primarysubcategoryname": "Casual Dining",
"primarysubcategoryslug": "casualdining",
"foodtype": "American",
"foodtypeid": 13,
"ranking": 3,
"region1": false,
"region2": false,
"region3": true,
"region4": false
},
{
"$id": "2",
"id": 1026,
"name": "#1 Wok",
"address": "1080 E. Highway 50",
"city": "Clermont",
"zip": "34711",
"phone": "352-555-2346",
"website": "",
"facebook": "",
"flickr": "",
"hasphoto": false,
"outdoordining": false,
"breakfastprice": "N/A",
"lunchprice": "Less than $10",
"dinnerprice": "Less than $10",
"description": "",
"primarycategoryname": "Dining",
"primarycategoryslug": "dining",
"primarysubcategoryname": "Casual Dining",
"primarysubcategoryslug": "casualdining",
"foodtype": "Asian",
"foodtypeid": 1,
"ranking": 1,
"region1": false,
"region2": false,
"region3": false,
"region4": true
}
]
I think you need a 'root' key in your JSON like follows:
[ restaurants: {

How to parse a small JSON file with jsmn on an embedded system?

I need to parse a small JSON file on an embedded system (only 10K RAM/flash). The JSON is:
{
"data1":[1,2,3,4,5,6,7,8,9],
"data2":[
[3,4,5,6,1],
[8,4,5,6,1],
[10,4,5,3,61],
[3,4,5,6,1],
[3,4,5,6,1],
[3,4,5,6,1]
]}
jsmn looks great to fit the requirement, but it's not like most JSON parsers, since it only gives you tokens. I tried, but could not figure it out.
Could someone share an example of how to parse it with jsmn?
jsmn will give you a set of tokens referring to the tokens in your JSON reading left to right.
In your case:
token[0]: (outer) object, 2 children
token[1]: string token ("data1")
token[2]: array, 9 children
token[3]: primitive token (1)
etc...
The basic code to do the parsing is:
int resultCode;
jsmn_parser p;
jsmntok_t tokens[128]; // a number >= total number of tokens
jsmn_init(&p);
resultCode = jsmn_parse(&p, yourJson, tokens, 256);
The other trick is getting the value of a token. The token contains the start and end points of the data on your original string.
jsmntok_t key = tokens[1];
unsigned int length = key.end - key.start;
char keyString[length + 1];
memcpy(keyString, &yourJson[key.start], length);
keyString[length] = '\0';
printf("Key: %s\n", keyString);
With that you should be able to figure you how to iterate through your data.
I was curious as about this as well, so I made a small program to show the structure of the tokens array:
This program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "jsmn.h"
jsmntok_t t[512];
char jsonStr[512*1024];
int main()
{
size_t pos = 0;
int c;
while ((c = getchar()) != EOF)
{
jsonStr[pos] = c;
++pos;
if (pos == sizeof(jsonStr)) break;
}
jsonStr[pos] = 0;
jsmn_parser p;
jsmn_init(&p);
int tCount = jsmn_parse(&p, jsonStr, strlen(jsonStr), t, sizeof(t)/sizeof(*t));
for (int i = 0; i != tCount; ++i)
{
jsmntok_t *token = t + i;
char * type = 0;
switch (token->type)
{
case JSMN_PRIMITIVE:
type = "PRIMITIVE";
break;
case JSMN_OBJECT:
type = "OBJECT";
break;
case JSMN_ARRAY:
type = "ARRAY";
break;
case JSMN_STRING:
type = "STRING";
break;
default:
type = "UNDEF";
}
#ifdef JSMN_PARENT_LINKS
printf("node: %4d, %9s, parent: %4d, children: %5d, data:\n%.*s, \n", i, type, token->parent, token->size, token->end-token->start, jsonStr+token->start);
#else
printf("node: %4d, %9s, children: %5d, data:\n%.*s, \n", i, type, token->size, token->end-token->start, jsonStr+token->start);
#endif
}
}
prints this json (taken from: https://en.wikipedia.org/wiki/JSON):
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
},
{
"type": "mobile",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
}
as:
node: 0, OBJECT, parent: -1, children: 8, data:
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
},
{
"type": "mobile",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
},
node: 1, STRING, parent: 0, children: 1, data:
firstName,
node: 2, STRING, parent: 1, children: 0, data:
John,
node: 3, STRING, parent: 0, children: 1, data:
lastName,
node: 4, STRING, parent: 3, children: 0, data:
Smith,
node: 5, STRING, parent: 0, children: 1, data:
isAlive,
node: 6, PRIMITIVE, parent: 5, children: 0, data:
true,
node: 7, STRING, parent: 0, children: 1, data:
age,
node: 8, PRIMITIVE, parent: 7, children: 0, data:
25,
node: 9, STRING, parent: 0, children: 1, data:
address,
node: 10, OBJECT, parent: 9, children: 4, data:
{
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
node: 11, STRING, parent: 10, children: 1, data:
streetAddress,
node: 12, STRING, parent: 11, children: 0, data:
21 2nd Street,
node: 13, STRING, parent: 10, children: 1, data:
city,
node: 14, STRING, parent: 13, children: 0, data:
New York,
node: 15, STRING, parent: 10, children: 1, data:
state,
node: 16, STRING, parent: 15, children: 0, data:
NY,
node: 17, STRING, parent: 10, children: 1, data:
postalCode,
node: 18, STRING, parent: 17, children: 0, data:
10021-3100,
node: 19, STRING, parent: 0, children: 1, data:
phoneNumbers,
node: 20, ARRAY, parent: 19, children: 3, data:
[
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
},
{
"type": "mobile",
"number": "123 456-7890"
}
],
node: 21, OBJECT, parent: 20, children: 2, data:
{
"type": "home",
"number": "212 555-1234"
},
node: 22, STRING, parent: 21, children: 1, data:
type,
node: 23, STRING, parent: 22, children: 0, data:
home,
node: 24, STRING, parent: 21, children: 1, data:
number,
node: 25, STRING, parent: 24, children: 0, data:
212 555-1234,
node: 26, OBJECT, parent: 20, children: 2, data:
{
"type": "office",
"number": "646 555-4567"
},
node: 27, STRING, parent: 26, children: 1, data:
type,
node: 28, STRING, parent: 27, children: 0, data:
office,
node: 29, STRING, parent: 26, children: 1, data:
number,
node: 30, STRING, parent: 29, children: 0, data:
646 555-4567,
node: 31, OBJECT, parent: 20, children: 2, data:
{
"type": "mobile",
"number": "123 456-7890"
},
node: 32, STRING, parent: 31, children: 1, data:
type,
node: 33, STRING, parent: 32, children: 0, data:
mobile,
node: 34, STRING, parent: 31, children: 1, data:
number,
node: 35, STRING, parent: 34, children: 0, data:
123 456-7890,
node: 36, STRING, parent: 0, children: 1, data:
children,
node: 37, ARRAY, parent: 36, children: 0, data:
[],
node: 38, STRING, parent: 0, children: 1, data:
spouse,
node: 39, PRIMITIVE, parent: 38, children: 0, data:
null,
You can use tiny-json. It gives you more than tokens. I have used with microcontrollers of 16-bits and 32-bits and it works fine.
char str[] = "{"
"\"data1\":[1,2,3,4,5,6,7,8,9],"
"\"data2\":["
"[3,4,5,6,1],"
"[8,4,5,6,1],"
"[10,4,5,3,61],"
"[3,4,5,6,1],"
"[3,4,5,6,1],"
"[3,4,5,6,1]"
"]"
"}";
puts( str );
json_t pool[64];
json_t const* root = json_create( str, pool, 64 );
json_t const* data1 = json_getProperty( root, "data1" );
if ( data1 && JSON_ARRAY == json_getType( data1 ) ) {
json_t const* field = json_getChild( data1 );
while( field ) {
if ( JSON_INTEGER == json_getType( field ) ) {
long long int data = json_getInteger( field );
printf("Integer from data1: %lld\n", data );
}
field = json_getSibling( field );
}
}
json_t const* data2 = json_getProperty( root, "data2" );
if ( data2 && JSON_ARRAY == json_getType( data2 ) ) {
json_t const* array = json_getChild( data2 );
while( array ) {
if ( JSON_ARRAY == json_getType( array ) ) {
puts("Array in data2");
json_t const* field = json_getChild( array );
while( field ) {
if ( JSON_INTEGER == json_getType( field ) ) {
long long int data = json_getInteger( field );
printf("Integer from array of data2: %lld\n", data );
}
field = json_getSibling( field );
}
}
array = json_getSibling( array );
}
}
I've just created jsmnRipper. This code lets you extract the tokens parsed with jsmn in a very simple way.
As an example here is the result of parsed the JSON message returned by ACRCloud
metadata.music[1].score:100:
metadata.music[1].album.name:The Best Of Depeche Mode Volume 1:
metadata.music[1].artists[0].name:Depeche Mode:
metadata.music[1].title:Enjoy The Silence (Remastered Version) (Original):
You can find the code for doing that at https://github.com/ipserc/jsmnRipper