JSON input string error using $.ajax - javascript

My web API accepts below JSON format (this is input parameter)
[{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"},
{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"
}
]
I am building request below in javascript.
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe'
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c'
var atrUserLegendsInputs
for (i = 0; i < list.get_items().get_count() ; i++)
{
atrUserLegendsInputs += { atrSpaUserId: administratorId, atrSpaClassLegendId: list.getItem(i).get_value(), atrSpaCityDistrictId: districtId } + ',';
}
atrUserLegendsInputs = atrUserLegendsInputs.substring(0, atrUserLegendsInputs.length - 1);
var legendIds = '[' + atrUserLegendsInputs + ']';
var atrDistrictLegend = { districtID: cityDistrictId, legendIDs: legendIds };
var test = JSON.stringify(atrDistrictLegend);
getting error message:
{["The input was not valid."]}
I am not sure whether I am doing the right way. I am new to Json and ajax calls. Can you one please help me to fix this issue

Try this code
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe';
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c';
//* create empty array for legends
var atrUserLegendsInputs = [];
for (i = 0; i < list.get_items().get_count() ; i++) {
//* put some values into legends' array
atrUserLegendsInputs.push({
atrSpaUserId: administratorId,
atrSpaClassLegendId: list.getItem(i).get_value(),
atrSpaCityDistrictId: districtId
});
}
var atrDistrictLegend = {
districtID: cityDistrictId,
legendIDs: atrUserLegendsInputs
};
var test = JSON.stringify(atrDistrictLegend);

Related

Cannot read property 'split' of null

I cannot display all the results because on the following channel there is no image and therefore I have the following message
$.get('https://wcf.tourinsoft.com/Syndication/3.0/cdt33/c616ab2a-1083-4ba0-b8e2-f7741e443e46/Objects?$format=json', function(data) {
//$.get('/json/ecranv2.json', function(data){
var blogs = data.value;
$(blogs).each(function() {
var manifs = this.Listingraisonsociale;
var ouverturecomp = this.Listinginformationsouverture;
var commune = this.Listingcommune;
var ouverture = this.Listingouverture;
var photos = this.Listingphotos;
//var datatest= this.Listingphotos;
let output = '';
let users = this.Listingphotos.split('$');
//var testsplit = split($);
for (var i = 0; i < users.length; i++) {
console.log(users[i]);
output += '<img src=' + users[i] + '?width=150&height=150&crop=1>';
}
$('.target').append('<p>' + manifs + '</p><span>' + output + '</span>');
});
});
The one index does not have a value for the property. It is null, so you need to check to see if it is null before you try to use split on it. A simple truthy check will work in this case.
let users = this.Listingphotos ? this.Listingphotos.split('$') : [];
With it in place:
$.get('https://wcf.tourinsoft.com/Syndication/3.0/cdt33/c616ab2a-1083-4ba0-b8e2-f7741e443e46/Objects?$format=json', function(data) {
//$.get('/json/ecranv2.json', function(data){
var blogs = data.value;
$(blogs).each(function() {
console.log(this);
var manifs = this.Listingraisonsociale;
var ouverturecomp = this.Listinginformationsouverture;
var commune = this.Listingcommune;
var ouverture = this.Listingouverture;
var photos = this.Listingphotos;
//var datatest= this.Listingphotos;
let output = '';
let users = this.Listingphotos ? this.Listingphotos.split('$') : [];
//var testsplit = split($);
for (var i = 0; i < users.length; i++) {
console.log(users[i]);
output += '<img src=' + users[i] + '?width=150&height=150&crop=1>';
}
$('.target').append('<p>' + manifs + '</p><span>' + output + '</span>');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="target"></div>
split is a method on string objects, which will be called on an actual string's reference.
So in your case, the split is not being called on a string, and the error message clearly states that we are using split over a null object. So make sure the object you are working on is an actual string, and work on it accordingly.
split mdn

How to pass dynamic string as dataset in charts.js

I am trying to pass a dynamically created value(newdata) in the dataset field of the chart.
var data = {
labels: bottomlabel,
datasets: newdata};
how I am getting data is using a for-loop :
for(i = 0; i < actual_JSON.length-1; i++){
dslabel = actual_JSON[i].Client;
dsdata = actual_JSON[i].Customer +"," +actual_JSON[i].Internal;
gcolor = dsbgcolor[i];
borcolor = dsborcolo[i];
if(i == actual_JSON.length-2)
{
prefinalds += "{label: "+dslabel+",data: ["+dsdata+"],backgroundColor: "+dsbgcolor[i]+",borderColor: "+dsborcolo[i]+",fill: "+fill+",lineTension: "+lt+",radius: "+rad+"}";
}
else
{
prefinalds += "{label: "+dslabel+",data: ["+dsdata+"],backgroundColor: "+dsbgcolor[i]+",borderColor: "+dsborcolo[i]+",fill: "+fill+",lineTension: "+lt+",radius: "+rad+"},";
}
}
and then creating 'data' :
newdata= "["+prefinalds+"]";
Now, when I am passing the data in 'datasets: newdata'. I am getting a blank chart. Please suggest.
P.S. I tried, JSON.parse() but it didn't work.
Have you tried this one?
var prefinallds = [];
for(i = 0; i < actual_JSON.length-1; i++){
var data = {};
dslabel = actual_JSON[i].Client;
dsdata = actual_JSON[i].Customer +"," +actual_JSON[i].Internal;
gcolor = dsbgcolor[i];
borcolor = dsborcolo[i];
if(i == actual_JSON.length-2)
{
data.label = dslabel;
data.data = dsdata;
data.backgroundColor = dsbgcolor[i];
data.borderColor = dsborcolo*emphasized text*[i];
data.radius = rad;
}
else
{
data.label = dslabel;
data.data = dsdata;
data.backgroundColor = dsbgcolor[i];
data.borderColor = dsborcolo*emphasized text*[i];
data.radius = rad;
}
prefinallds.push(data);
}
// convert to json
JSON.parse(prefinallds);
You tried to convert a string into JSON format which is not recommended. I strongly courage developers to use an actual object to parse their data.

Unable to parse json using javascript

I have a json which i'm trying to parse it using javascript. Iteration count and the pages getting appended to it are going to be dynamic.
Expected Result
Just like the above image i'm able to take dynamic iteration keys from the below mentioned json.
Iteration.json
{
"count":[
{
"iteration1":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
},
{
"iteration2":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
}
]
}
When i click on iteration it has to populate the corresponding pagenames for that particular iteration as shown in expected result image. But what i get actually is (refer the image below):
Please find the code that i tried:
var pagenamearray = [];
$.getJSON("iteration.json", function(json) {
var hits = json.count;
var iterations, tnname, iteration;
for (var k in hits) {
var value;
if (hits.hasOwnProperty(k)) {
value = hits[k];
var iteratearray = [];
for (var j in value) {
if (value.hasOwnProperty(j)) {
j;
var check = value[j];
for (var i in check) {
if (check.hasOwnProperty(i)) {
var test = check[i];
for (var t in test) {
if (test.hasOwnProperty(t)) {
var pagename = JSON.stringify(t)
var arr = []
if (pagename.includes("PageName")) {
//alert("Key is " +pagename + ", value is" + JSON.stringify(test[t]));
for (var it = 0; it < hits.length; it++) {
if ((Object.keys(hits[it])).includes(j)) {
var pagenamevalue = test[t];
arr[it] = [];
arr.push(pagenamevalue);
}
}
}
//alert(arr)
}
pagenamearray.push(arr);
}
}
}
}
var row = document.createElement('div');
row.setAttribute("class", "row");
row.setAttribute("id", j)
var gridWidth = document.createElement('div');
gridWidth.setAttribute("class", "col-lg-12");
var panelRoot = document.createElement('div');
panelRoot.setAttribute("class", "panel panel-default");
var panelHeading = document.createElement('div');
panelHeading.setAttribute("class", "panel-heading");
var heading3 = document.createElement('a');
heading3.setAttribute("class", "panel-title");
var icon = document.createElement('i');
icon.setAttribute("class", "fa fa-long-arrow-right fa-fw");
heading3.appendChild(icon);
heading3.innerHTML = j;
heading3.setAttribute("onclick", "doit('" + j + "');");
panelHeading.appendChild(heading3);
/* var panelBody=document.createElement('div');
panelBody.setAttribute("class","panel-body");
panelBody.setAttribute("id","panellinks");*/
panelRoot.appendChild(panelHeading);
// panelRoot.appendChild(panelBody)
gridWidth.appendChild(panelRoot);
row.appendChild(gridWidth);
document.getElementById("analysis").appendChild(row);
}
}
}
});
function doit(value) {
var ul = document.getElementById(value);
if (ul != undefined) {
$("#" + "expandlinks").remove();
$("#" + value + value).remove();
}
var accordion = document.getElementById(value);
var panelBody = document.createElement('div');
panelBody.setAttribute("class", "panel-body");
panelBody.setAttribute("id", "expandlinks")
var tablediv = document.createElement('div')
var tablelink = document.createElement('a');
tablediv.appendChild(tablelink);
var graphdiv = document.createElement('div')
var graphlink = document.createElement('a');
graphdiv.appendChild(graphlink);
var recommndiv = document.createElement('div');
var recommendlink = document.createElement('a');
recommndiv.appendChild(recommendlink)
//alert(pagenamearray.length)
tablelink.innerHTML = pagenamearray;
/*graphlink.innerHTML="Timeline View";
recommendlink.innerHTML="Recommendations";*/
panelBody.appendChild(tablediv);
panelBody.appendChild(recommndiv);
panelBody.appendChild(graphdiv);
accordion.appendChild(panelBody);
}
Any advise on how to achieve this would be of great help. Thanks in advance.
I think the problem is how you assign the pagenamearray to tablelink.innerHTML. This converts the array to a string, converting all elements in the array to a string too and separating them by a comma each. However, your pagenamearray contains some empty arrays too; these will convert to an empty string in the process, but will still have a comma before and after them.
In your example code above, the pagenamearray will end up with a value of [[[],"T01_Launch"],[[],"T02_Login"],[null,[],"T01_Launch"],[null,[],"T02_Login"]] - when converted to a String, this will result in ",T01_Launch,,T02_Login,,,T01_Launch,,,T02_Login". So instead of assigning it to the innerHTML value directly, you'll first have to filter out the empty arrays and null values.

jsonp request does not show facebook data

I am using JSON to display info from a site. The book example works which gave me a custom website to get information from worked, but when I replaced the url with Spider man's facebook page, it seems as if the data is processing, but the information does not display. Is there some crucial step that I am missing.
var lastReporttime = 0;
window.onload= function(){
setInterval(handleRefresh,3000);
}
function updateSales(sales) {
var salesDiv= document.getElementById("sales");
for (var i = 0; i < sales.length; i++) {
var sale = sales[i];
var div = document.createElement("div");
div.innerHTML = sale.category + sale.about + "spiderman";
salesDiv.appendChild(div);
}
if (sales.length > 0) { lastReporttime = sales[sales.length-1].time; }
}
function handleRefresh() {
var url = "http://graph.facebook.com/SpiderManDVD"
+ "callback=updateSales"
+ "&lastreporttime=" + lastReporttime
+ "&random="+ (new Date()). getTime();
var newScriptElement= document.createElement("script");
newScriptElement.setAttribute("src", url);
newScriptElement.setAttribute("id", "jsonp");
var oldScriptElement= document.getElementById("jsonp");
var head= document.getElementsByTagName("head")[0];
if (oldScriptElement == null) {
head.appendChild(newScriptElement);
} else {
head.replaceChild(newScriptElement, oldScriptElement);
}
}
Response you received from your book example returns a JSON Array which is perfectly handled in your code.
But response from facebook api returns a JSON object which is breaking your code.
Check both the urls and update the logic inside updateSales to handle both JSON Array as well as JSONObject as per your use case.
Something like this
function updateSales(sales) {
var salesDiv= document.getElementById('sales');
// Check if sales is array or not (One of the crude ways, ofcourse not best but may work for you)
if (typeof sales.length == 'undefined') {
sales = [sales];
}
for (var i = 0; i < sales.length; i++) {
var sale = sales[i];
var div = document.createElement("div");
div.innerHTML = sale.category + sale.about + "spiderman";
salesDiv.appendChild(div);
}
if (sales.length > 0) {
lastReporttime = sales[sales.length-1].time;
}
}

Getting Object Expected Error in Server Side Javascript Code

I am getting an error stating that an object is expected in the below code. The error is:
Object Expected: this.regionalRankings[worldRegion][rankType] = this.getRankings(rankType, this.regionalRankingKey[worldRegion]);
Declarations...
this.regions = {};
this.regions = ["US", "Europe", "Asia"];
this.regionalRankingKey = ["SP500", "GBE", "CNG"]; //this is the ranking model key for pulling up the rankings object.
this.rankingTypes = ["gainers", "losers", "actives"];
this.regionalRankings = {};
this.rankingWSODIssues = [];
marketSummary_data.prototype.initRankingsNew = function(){
for(var worldRegion in this.regions){
for (var rankType in this.rankingTypes){
//this is the line getting the error.
this.regionalRankings[worldRegion][rankType] = this.getRankings(rankType, this.regionalRankingKey[worldRegion]);
for(var i = 0; i < 5; i++){
this.rankingWSODIssues.push(this.regionalRankings[worldRegion][rankType].value("Result[0].Row[" + i + "].WSODIssue"));
}
}
}
for(var item in this.rankingWSODIssues){
Response.Write("<p>" + item + ": " + rankingWSODIssues[item] + "</p>");
}
}
the function this.getRankings returns an object.
marketSummary_data.prototype.getRankings = function(rankingType, rankingSet){
//ranking types Epctchg+ (pct gainers)
//Epctchg- (pct losers)
//Edollar+ (net gainers)
//Edollar- (net losers)
//Evol+ (highest volume)
//rankingSets
if (rankingType == "gainers"){
rankingType = "Epctchg+";
}
if (rankingType == "losers"){
rankingType = "Epctchg-";
}
if (rankingType == "actives"){
rankingType = "Evol+";
}
var rankings = User.CreateObject("WIT.Rankings.1")
rankings.SetVariableName("Rankings")
rankings.SetInput("Ranking.RT", 0)
rankings.SetInput("Ranking.Type", rankingType)
rankings.SetInput("Ranking.Set", rankingSet)
rankings.SetInput("Ranking.Rows", 5)
rankings.SetInput("Ranking.Symbolset", "BridgeStreet");
rankings.SetInput("Ranking.MinPrice", 0); // only want stocks trading higher> 0
rankings.Retrieve();
return rankings;
}
Any ideas on what I am doing wrong here?
The problem is that this.regionalRankings[worldRegion][rankType] requires that this.regionalRankings[worldRegion] be something, however this.regionalRankings is an empty object, so an "Object is Required."
I think what you intended to do is:
for(var worldRegion in this.regions){
this.regionalRankings[worldRegion] = {}; // Make it into an object.
for (var rankType in this.rankingTypes){
this.regionalRankings[worldRegion][rankType] = ...
}
}

Categories

Resources