JSON Help regarding objects and stringify - json

I have a variable here which equates to
var4 = "{name: 'TestUser', data: [1.0, 0.8, 0.64]}"
series: [
{
name: 'TestUser',
data: [1.0, 0.8, 0.64]
}
],
I would like to find out how I can put var4 into my series instead of typing in the data. I have read up about JSON.stringify and parse but it doesn't seem to work here.

Use JSON.parse(str) to turn a string into an object. Also define the JSON variable name as a string.
series = [
{
'name': 'TestUser',
'data': [1.0, 0.8, 0.64]
},
];
series.push(JSON.parse(var4));
Or maybe this is what you want:
myJsonObj = {
'series': [
{
'name': 'TestUser',
'data': [1.0, 0.8, 0.64]
},
]
}
myJsonObj.series.push(JSON.parse(var4));
Or this:
jsonObj = JSON.parse(var4);
myJsonObj = {
'series': [
{
'name': jsonObj.name,
'data': jsonObj.data
},
]
}

Related

Remove empty elements from nested JSON

I have a nested json with an arbitrary depth level :
json_list = [
{
'class': 'Year 1',
'room': 'Yellow',
'students': [
{'name': 'James', 'sex': 'M', 'grades': {}},
]
},
{
'class': 'Year 2',
'info': {
'teachers': {
'math': 'Alan Turing',
'physics': []
}
},
'students': [
{ 'name': 'Tony', 'sex': 'M', 'age': ''},
{ 'name': 'Jacqueline', 'sex': 'F' },
],
'other': []
}
]
I want to remove any element that its value meet certain criteria.
For example:
values_to_drop = ({}, (), [], '', ' ')
filtered_json = clean_json(json_list, values_to_drop)
filtered_json
Expected Output of clean_json:
[
{
'class': 'Year 1',
'room': 'Yellow',
'students': [
{'name': 'James', 'sex': 'M'},
]
},
{
'class': 'Year 2',
'info': {
'teachers': {
'math': 'Alan Turing',
}
},
'students': [
{ 'name': 'Tony', 'sex': 'M'},
{ 'name': 'Jacqueline', 'sex': 'F'},
]
}
]
I thought of something like first converting the object to string using json.dumps and then looking in the string and replacing each value that meets the criteria with some kind of flag to filter it after before reading it again with json.loads but I couldn't figure it out and I don't know if this is the way to go
I managed to get the desired output by tweaking this answer a bit:
def clean_json(json_obj, values_to_drop):
if isinstance(json_obj, dict):
json_obj = {
key: clean_json(value, values_to_drop)
for key, value in json_obj.items()
if value not in values_to_drop}
elif isinstance(json_obj, list):
json_obj = [clean_json(item, values_to_drop)
for item in json_obj
if item not in values_to_drop]
return json_obj

Deleting deep in an array with immutablejs

I am trying to perform a complex deletion in Immutablejs, without, what I always seem to do, converting to JS in the middle of the process.
In the following array, I would like to delete every second {y: } object
series: [
{
name:"1",
data: [
{y: 1},
{y: 2},
{y: 3}
]
},
{
name:"2",
data: [
{y: 1},
{y: 2},
{y: 3}
]
},
{
name:"3",
data: [
{y: 1},
{y: 2},
{y: 3}
]
}
]
So that I would get this :
series: [
{
name:"1",
data: [
{y: 1},
{y: 3}
]
},
{
name:"2",
data: [
{y: 1},
{y: 3}
]
},
{
name:"3",
data: [
{y: 1},
{y: 3}
]
}
]
Can someone point me in the correct direction how to do this with ImmutableJS? If I just use filter or array reduce I can arrive at a really clean solution that looks like this :
series.forEach(function (elem) {
let data = elem.data;
data.splice(index, 1);
});
I am just hoping that immutable has an equally clean looking solution.
The doc for removeIn doesn't go deep enough :
https://facebook.github.io/immutable-js/docs/#/removeIn
You're modifying every element of series so I think you're on the right track with .map(). Then you want to use .removeIn to deeply remove something.
let seriesList = Immutable.fromJS(series)
seriesList = seriesList.map(elem =>
elem.removeIn(['data', indexToRemove]));
// equivalent form with .update() instead of .removeIn()
seriesList = seriesList.map(elem =>
elem.update('data', data => data.remove(indexToRemove)));
I managed to do it using 'map' from Immutable List. This worked for me :
seriesList = Immutable.List(seriesList);
seriesList = seriesList.map(
elem => {
let data = elem.getIn(['data'])
data = data.remove(index)
elem = elem.setIn(['data'], data)
return elem
})
Anyone have something better?

Get Array Of Object On ajax Call success

I will make Ajax call on my Controller action method. I want result of JSON in this format.
// array of all brands
var brands = [
{ brandId: 1, name: "Ford" },
{ brandId: 2, name: "BMW" }
];
for this i will make another call
// array of all models
var models = [
{ modelId: 1, name: "Explorer", brandId: 1},
{ modelId: 2, name: "Focus", brandId: 1},
{ modelId: 3, name: "X3", brandId: 2},
{ modelId: 4, name: "X5", brandId: 2}
];
How can i do that please guide me.
You can use following code to solve your problem
public ActionResult SomeActionMethod(int id)
{
return Json(new {foo="bar", baz="Blech"});
}
Method from the jquery getJSON method by simply...
$.getJSON("../SomeActionMethod", { id: someId },
function(data) {
alert(data.foo);
alert(data.baz);
}
);
To serialize json in your controller, may be you can use http://www.newtonsoft.com/json/help/html/serializingjson.htm

I have a json response and my Ember model is not matching for it

My Json response is like this
{
"object": {
"assignments": [
{
"assignmentId": 14706368,
"sectionId": 0,
"assignmentType": "FILEATTACH",
"assignmentTitle": "file attachment A",
"assignmentStartDate": "01/01/1900",
"assignmentStartTime": "01:00AM",
"assignmentDueDate": "01/01/2100",
"assignmentDueTime": "01:00AM",
"isMarathonChain": "No",
"assignmentTimeLimit": 0,
"assignmentTimeRemaining": "0",
"marathonAssignmentStatus": "MARATHON_NOT_ASSOCIATED",
"showAssignmentAttemptsAndPasswordDetails": false,
"assignmentAttemptsTaken": 0,
"assignmentAttemptsAllowed": "1",
"showPasswordForm": false,
"isStartAssignment": true,
"isResumeAssignment": false,
"isSubmitAssignment": false,
"passwordRequired": false,
"isConvertToGeniusEnabled": false,
"draftNumber": 0,
"studentExceptionExistsForDueDate": false,
"isPastUploadDate": false,
"showMarathonPrerequisiteInfo": false
}
],
"sections": [
{
"sectionId": 241409387,
"courseId": 241409386,
"sectionName": "Section01"
}
],
"courses": [
{
"courseId": 241409386,
"courseName": "Tricon.Connect_01",
"showDiscipline": false
}
],
"users": [
{
"userId": 1000321061,
"firstName": "Ragu �������&^&",
"lastName": "+##)()XYZ �^^������",
"userType": "S"
}
],
"returnLMS": [
{
"returnUrl": "bb"
}
]
}
}
My data model is like this
var attr = DS.attr;
App.About = DS.Model.extend({
object: DS.hasMany('object')
});
App.Object = DS.Model.extend({
assignments: DS.hasMany('assignments'),
sections: DS.hasMany('sections'),
courses: DS.hasMany('courses'),
users: DS.hasMany('users'),
returnLMS: DS.hasMany('returnLMS')
});
App.Assignments = DS.Model.extend({
assignmentId: attr('number'),
sectionId:attr('number'),
assignmentType:attr('string'),
assignmentTitle:attr('string'),
assignmentStartDate:attr('string'),
assignmentStartTime:attr('string'),
assignmentDueDate:attr('string'),
assignmentDueTime:attr('string'),
isMarathonChain:attr('boolean'),
assignmentTimeLimit:attr('number'),
assignmentTimeRemaining:attr('number'),
marathonAssignmentStatus:attr('string'),
showAssignmentAttemptsAndPasswordDetails:attr('boolean'),
assignmentAttemptsTaken:attr('number'),
assignmentAttemptsAllowed:attr('number'),
showPasswordForm:attr('boolean'),
isStartAssignment:attr('boolean'),
isResumeAssignment:attr('boolean'),
isSubmitAssignment:attr('boolean'),
passwordRequired:attr('boolean'),
isConvertToGeniusEnabled:attr('boolean'),
draftNumber:attr('number'),
studentExceptionExistsForDueDate:attr('boolean'),
isPastUploadDate:attr('boolean'),
showMarathonPrerequisiteInfo:attr('boolean')
});
App.Sections = DS.Model.extend({
sectionId: attr('number'),
courseId: attr('number'),
sectionName: attr('string')
});
App.Courses = DS.Model.extend({
courseId: attr('number'),
courseName: attr('string'),
showDiscipline: attr('boolean')
});
App.Users = DS.Model.extend({
userId: attr('number'),
firstName: attr('string'),
lastName: attr('string'),
userType:attr('string')
});
App.ReturnLMS = DS.Model.extend({
returnUrl: attr('string')
});
In this App.About is my route name so I have created object inside this and rest of it as follows.
No i am getting my response from restadapter but somehow it is not matching it with my model format and my model object show empty.
Take a look at the JSON conventions Ember Data is expecting.
You can also input your models into a neat tool called the ember-data-model-maker, and see what the server responses should be.
If you don't have control over your server responses, you'll need to extend DS.RESTAdapter to manipulate your JSON to get it into the form Ember Data expects.

dynamic create json for treeview

I want to turn json
var treeNodes = [ {managerid:root,Employeeid:01},
{managerid:01,Employeeid:11},
{managerid:01,Employeeid:22},
{managerid:22,Employeeid:33},
{managerid:22,Employeeid:44}
];
into json like this using javascript.
json={
id:root,
children[{
id:01,
children[
{id:11},
{id:22}
]
children[
{id:33},
{id:44}
]
}
Can someone help with java script function?
First of all, your current JSON is incorrect:
var json = {
id: root,
children: [
{
id: 01,
children: [
{id: 11},
{id: 22}
]
},
{
children: [
{id: 33},
{id: 44}
]
}
]
};
Second, could you give more information about your table Employee?