how to fetch my syllables so I can console log them - javascript

the JSON looks like this:
{
"main_object": {
"id": "new",
"getExerciseTitle": "TestAfterCodeCleaning",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "TestAfterCodeCleaning",
"language": "nl_NL",
"exercises": [
{
"word": "testikels",
"syllables": [
"test",
"ikels",
"",
""
]
}
]
},
"dataType": "json"
}
}
This is how I try to fetch the syllables so I can console.log() them:
var jsyl = json.main_object.main_object.exercises.syllables;
the problem however: This shows in my console.log() undefined. Why and how?
The complete code looks like this:
function prepareCheck() {
$.getJSON('json_files/jsonData_' + ID + '.json', function(json) {
$(document).on('keyup', '.syl-input', function() {
var syllableval = $(idsyll).val();
var jsyl = json.main_object.main_object.exercises.syllables;
});
});
}
Note: The JSON has one syllables, because I thought it would be easier for you to read, however what should be done to fetch all the syllables (in case there are more then one array of syllables).

Use exercises[0] instead of exercises because exercises is an array of objects in this case only having one item at index 0.
var jsyl = json.main_object.main_object.exercises[0].syllables;
var json = {
"main_object": {
"id": "new",
"getExerciseTitle": "TestAfterCodeCleaning",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "TestAfterCodeCleaning",
"language": "nl_NL",
"exercises": [
{
"word": "testikels",
"syllables": [
"test",
"ikels",
"",
""
]
}
]
},
"dataType": "json"
}
}
var jsyl = json.main_object.main_object.exercises[0].syllables;
console.log(jsyl); // [ 'test', 'ikels', '', '' ]

Related

Tableau Web Data Connector error

I am creating a Tableau Web Data Connector as per the documentation HERE.
I am running the Simulator and have setup a HTML page (as per tutorial) which calls a Javascript file that runs the Tableau WDC script as below.
(function () {
var myConnector = tableau.makeConnector();
myConnector.init = function(initCallback) {
initCallback();
tableau.submit();
};
myConnector.getSchema = function (schemaCallback) {
var cols = [
{ id : "date_of_work", alias : "Date of Work", dataType: tableau.dataTypeEnum.date },
{ id : "supervisor", alias : "Supervisor", dataType: tableau.dataTypeEnum.string }
];
var tableInfo = {
id : "test",
alias : "test",
columns : cols
};
schemaCallback([tableInfo]);
};
myConnector.getData = function (table, doneCallback) {
$.getJSON("http://myDataCall.php", function(response) {
// ERROR HERE!
var resp = response.job.job_workflows; // Response
var parsedResp = JSON.parse(resp); // Parse the response
var tableData = []; // Temp array
// Iterate over the JSON object
for (var i = 0, len = resp.length; i < len; i++) {
tableData.push({
"date_of_work": parsedResp[i]['job_status'],
"supervisor": parsedResp[i]['job_workflow_1197927'],
});
}
table.appendRows(tableData);
doneCallback();
});
};
tableau.registerConnector(myConnector);
})();
When I run the script I get the error: The WDC reported an error:
Uncaught SyntaxError: Unexpected token o in JSON at position 1 stack:SyntaxError:
Unexpected token o in JSON at position 1 at JSON.parse () at Object.success
The (abbreviated) JSON that is being returned looks as follows:
{
"employee": {
"id": 23940,
},
"company": {
"id": 1059,
},
"job": {
"id": 13712707,
"job_status_logs": [{
"id": 17330391,
}],
"company": {
"id": 1059,
},
"created_by": {
"id": 23940,
},
"job_workflows": [{
"id": 1087689283,
"job_id": 13712707,
"employee_id": null,
"template_workflow_id": 1251218,
"name": "Date of work",
"action": "datepicker",
"optional": 0,
"action_values": "",
"action_value_entered": "2017-10-12",
"nested_workflow_id": 0,
}, {
"id": 1087689284,
"job_id": 13712707,
"employee_id": null,
"template_workflow_id": 1251219,
"name": "Supervisor",
"action": "list",
"optional": 0,
"action_values": "John Doe",
"action_value_entered": "John Doe",
"nested_workflow_id": 0,
}],
"job_fields": [{
"id": 50456098,
}],
"job_status_change_messages": [{
"id": 59957985}],
"job_assets":[]
}
}
I am trying to access the job.job_workflows.action_value_entered value but keep getting the error as above.
How can I fix this error?
There are a couple of issues here.
1) The JSON sent back from your server is invalid. Here is the valid version. I recommend using a site like https://jsonformatter.curiousconcept.com/ to validate your JSON.
{
"employee": {
"id": 23940
},
"company": {
"id": 1059
},
"job": {
"id": 13712707,
"job_status_logs": [{
"id": 17330391
}],
"company": {
"id": 1059
},
"created_by": {
"id": 23940
},
"job_workflows": [{
"id": 1087689283,
"job_id": 13712707,
"employee_id": null,
"template_workflow_id": 1251218,
"name": "Date of work",
"action": "datepicker",
"optional": 0,
"action_values": "",
"action_value_entered": "2017-10-12",
"nested_workflow_id": 0
}, {
"id": 1087689284,
"job_id": 13712707,
"employee_id": null,
"template_workflow_id": 1251219,
"name": "Supervisor",
"action": "list",
"optional": 0,
"action_values": "John Doe",
"action_value_entered": "John Doe",
"nested_workflow_id": 0
}],
"job_fields": [{
"id": 50456098
}],
"job_status_change_messages": [{
"id": 59957985}],
"job_assets":[]
}
}
2) jQuery's getJson method returns an object, so you don't need to parse it. You can just use the resp variable directly like so:
var resp = response.job.job_workflows; // Response
var tableData = []; // Temp array
// Iterate over the JSON object
for (var i = 0, len = resp.length; i < len; i++) {
tableData.push({
"date_of_work": resp[i]['job_status'],
"supervisor": resp[i]['job_workflow_1197927'],
});
}
table.appendRows(tableData);
doneCallback();
Fixing those two issues should unblock you. However, you'll want to think through what data you are sending back. The current values you are sending back do not exist in the JSON (i.e. resp[i]['job_workflow_1197927']).
Instead, you could do something like this: resp[1].job_id, which would give you the job_id of each job_workflow.

Filter Json Using Javascript

Hello Can you help me to filter such Json Object:
{
"data": {
"statuses": [{
"entities": {
"urls": [],
"user_mentions": [{
"screen_name": "name1"
}]
},
"entities": {
"urls": [],
"user_mentions": [{
"screen_name": "name2"
}]
},
"entities": {
"urls": [],
"user_mentions": [{
"screen_name": "name3"
}]
}
}]
}
}
I need to get array with values of each key screen_name.
For example: array = ["name1","name2","name3"]
How i can do it without frameworks with only JS?
Thanks for your help. I have updated Json to such like this:
var obj = {
"data": {
"statuses": [{
"urls": [],
"user_mentions": [{
"indices": [
3,
16
],
"id_str": "626444770",
"id": 626444770,
"name": "katheryn",
"screen_name": "sella_sandra"
}, {
"indices": [
"***",
"***"
],
"id_str": "21447363",
"id": 21447363,
"name": "KATY PERRY",
"screen_name": "katyperry"
}, {
"indices": [
"***",
"***"
],
"id_str": "21447363",
"id": 21447363,
"name": "KATY PERRY",
"screen_name": "floyd"
}]
}]
}
I'm wanna to get array of screen_names.I wrote such code.But when i use for.It doesn't work here:
console.log (statuses[0].user_mentions[i].screen_name)
I't silly mistake but I cannot find out how correct that. Help guys!
var statuses = obj.data.statuses;
for (var i=0; i<statuses.length; i++ )
{ if ( typeof statuses[0].user_mentions !== "undefined")
{
for (var i=0; i<statuses.length; i++){
console.log (statuses[0].user_mentions[i].screen_name);
}
}
else console.log ="No senders";
}
Your syntax is incorrect, since inside statuses array you cannot have another key value data.
Removing the entities key name assuming that it is simply an array of objects then try this
var obj = { "data": {
"statuses": [
{
"urls": [],
"user_mentions": [{
"screen_name": "name1"
}]
},
{
"urls": [],
"user_mentions": [{
"screen_name": "name2"
}]
},
{
"urls": [],
"user_mentions": [{
"screen_name": "name3"
}]
}
]
} };
var statuses = obj.data.statuses;
var names = [];
for (var counter = 0; counter < statuses.length; counter++ )
{
names.push( statuses[ counter ].user_mentions[0].screen_name );
}
console.log( names );
Given your updated data object, this returns an array of screen_names (with any duplicates removed. If you want to keep duplicates, declare names as an array and push to it instead.) I used a relatively verbose coding style to make it easier to see what's going on.
var obj = {
"data": {
"statuses": [{
"urls": [],
"user_mentions": [{
"indices": [3,16],
"id_str": "626444770",
"id": 626444770,
"name": "katheryn",
"screen_name": "sella_sandra"
}, {
"indices": ["***","***"],
"id_str": "21447363",
"id": 21447363,
"name": "KATY PERRY",
"screen_name": "katyperry"
}, {
"indices": ["***","***"],
"id_str": "21447363",
"id": 21447363,
"name": "KATY PERRY",
"screen_name": "floyd"
}]
}]
}
};
var names = {};
for (var i=0; i<obj.data.statuses.length; i++) {
if (obj.data.statuses[i]["user_mentions"]) {
var mentions = obj.data.statuses[i]["user_mentions"];
for (var j=0; j<mentions.length;j++) {
if (mentions[j]["screen_name"]) {
names[mentions[j]["screen_name"]] = 1;
}
}
}
}
var arrayOfScreenNames = Object.keys(names);
console.log(arrayOfScreenNames);

What is the proper way to run each function for many child nodes?

I have an array and many objects in it. I want to be able to run an each function to change every files/a with files/and in every subpage > file nodes. How can i do this with a proper each or loop function? I think about that and it is the structure below in my mind and looks like terrible solution.
$.each(main, function( index, value ) {
$.each(index.subpage, function( index, value ) {
$.each(index.files, function( index, value ) {
value.replace("files/a", "files/and");
});
});
});
The main object looks like below.
{
"main": [
{
"title": "AAA",
"hash": "a",
"subpage": [
{
"title": "b",
"hash": "b",
"subpage": [
{
"title": "c",
"hash": "c",
"subpage": [],
"files": [
{
"files/a/b/c/01_clandestino_dev%20%282%29.jpg": {}
},
{
"files/a/b/c/01_clandestino_dev%20%283%29.jpg": {}
}
],
"content": "",
"layout": "standart"
}
],
"files": [
{
"files/a/b/01_clandestino_dev%20%282%29.jpg": {}
},
{
"files/a/b/01_clandestino_dev%20%283%29.jpg": {}
}
],
"content": "asd123",
"layout": "standart"
}
],
"files": [
{
"files/a/01_clandestino_dev.jpg": {}
},
{
"files/a/01.Creative_Collective_Effect_Overview.jpg": {}
},
{
"files/a/01.Bor%C3%A5s_H%C3%B6gskola_Website_Narrow.jpg": {}
}
],
"content": "AAAb",
"layout": "standart",
"menuItem": "true"
}
]
}
Recursion is the only solution. You need to write a function that processes a "page":
process each subpage inside the current page using recursion
process each file inside the current page
Each file is an object with one key; you need to add the new key and remove the old key using the delete operator.
var o = {
"main": [{
"title": "AAA",
"hash": "a",
"subpage": [{
"title": "b",
"hash": "b",
"subpage": [{
"title": "c",
"hash": "c",
"subpage": [],
"files": [{
"files/a/b/c/01_clandestino_dev%20%282%29.jpg": {}
}, {
"files/a/b/c/01_clandestino_dev%20%283%29.jpg": {}
}],
"content": "",
"layout": "standart"
}],
"files": [{
"files/a/b/01_clandestino_dev%20%282%29.jpg": {}
}, {
"files/a/b/01_clandestino_dev%20%283%29.jpg": {}
}],
"content": "asd123",
"layout": "standart"
}],
"files": [{
"files/a/01_clandestino_dev.jpg": {}
}, {
"files/a/01.Creative_Collective_Effect_Overview.jpg": {}
}, {
"files/a/01.Bor%C3%A5s_H%C3%B6gskola_Website_Narrow.jpg": {}
}],
"content": "AAAb",
"layout": "standart",
"menuItem": "true"
}]
};
function process_page(page) {
if (page.main || page.subpage) {
$.each(page.main || page.subpage, function(i, subpage) {
process_page(subpage);
});
}
if (page.files) {
$.each(page.files, function(i, file) {
$.each(file, function(oldname, value) {
var newname = oldname.replace("files/a", "files/and");
console.log("old: " + oldname);
console.log("new: " + newname);
file[newname] = value;
delete file[oldname];
});
});
}
}
process_page(o);
console.log(o);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Searching JSON objects with JQuery

I have the following JSON object. Using JQuery I need to find the values of the following:
summary.nameValues.ID and detail.TypedNameValues.size
Could somebody please show how this can be achieved using JQuery?
[
{
"path": "\\Users\\john.smith\\test",
"summary": {
"NameValues": [
{
"Name": "Id",
"Values": [
"232639"
]
},
{
"Name": "City",
"Values": [
"London"
]
}
]
},
"detail": {
"String": "some data",
"Result": 0,
"TypedNameValues": [
{
"Name": "name1",
"Type": "string",
"Value": "data here!!"
},
{
"Name": "size",
"Type": "long",
"Value": "434353"
}
]
}
}
]
jQuery doesn't work on plain object literals. You can use the below function in a similar way to search all 'id's (or any other property), regardless of its depth in the object:
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
Use like so:
getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects
This answer taken from another thread. You may find more help here: use jQuery's find() on JSON object
Performing this kind of queries on JSON structures are trivial using DefiantJS (http://defiantjs.com). This lib extends the global object JSON with the method "search" - with which one can execute XPath expressive searches.
Check out this fiddle;
http://jsfiddle.net/hbi99/kLE2v/
The code can look like this:
var data = [
{
"path": "\\Users\\john.smith\\test",
"summary": {
"NameValues": [
{
"Name": "Id",
"Values": "232639"
},
{
"Name": "City",
"Values": "London"
}
]
},
"detail": {
"String": "some data",
"Result": 0,
"TypedNameValues": [
{
"Name": "name1",
"Type": "string",
"Value": "data here!!"
},
{
"Name": "size",
"Type": "long",
"Value": "434353"
}
]
}
}
],
res = JSON.search( data, '//*[Name="size"]' );
console.log( res[0].Value );
// 434353
Some one else as already answered, either way here is my version for the same.
<textarea id="ta" style="display:none;">[
{
"path": "\\Users\\john.smith\\test",
"summary": {
"NameValues": [
{
"Name": "Id",
"Values": [
"232639"
]
},
{
"Name": "City",
"Values": [
"London"
]
}
]
},
"detail": {
"String": "some data",
"Result": 0,
"TypedNameValues": [
{
"Name": "name1",
"Type": "string",
"Value": "data here!!"
},
{
"Name": "size",
"Type": "long",
"Value": "434353"
}
]
}
}
]</textarea>
Parser
var obj = $.parseJSON($('#ta').val());
var nameValues = obj[0].summary.NameValues;
var typedNameValues = obj[0].detail.TypedNameValues;
function getObjByName(o, name) {
for (var i = 0; i < o.length; i++) {
if (o[i].Name == name) {
return o[i];
}
}
return null;
}
alert(getObjByName(nameValues, 'Id').Values.join(", "));
alert(getObjByName(typedNameValues, 'size').Value);
A working fiddle for you on the same.
http://jsfiddle.net/3EVE4/

How to display an array returned by a json object (foreach dojo)

I have a json file returned as a json object (which is an array of arrays)...below is the returned json object
{
"Info": {
"Contact": ".... ",
"title": "..."
},
"details": [
{
"ID": 1,
"Question": "User ID",
"Information": "",
}, {
"ID": 2,
"Question": "Name",
"Information": "",
}, {
"ID": 3,
"Question": "Age",
"Information": "",
}
],
"list": [
{
"No": 1,
"response": ""
}, {
"No": 2,
"response": ""
}
]
}
Now i want to display only details...the below array
"Details": [
{
"ID": 1,
"Question": "User ID",
"Information": "",
}, {
"ID": 2,
"Question": "Name",
"Information": "",
}, {
"ID": 3,
"Question": "Age",
"Information": "",
}
],
How do i do this?? please help..
Thanks in advance.
1) parse the JSON into a javascript object
var parsedJSON = JSON.parse(jsonData);
2) access the properties you want
var details = parsedJSON.details;
edit: You are parsing your javascript object back into JSON, why??
working jsfiddle
var output = "";
for(var i=0; i<json.details.length; i++) {
var detail = json.details[i];
output += detail.ID +", "+ detail.Question +", "+ detail.Information +"\n";
}
alert(output);

Categories

Resources