Handle json response in 2D array - javascript

I am into some weird situation where JSON response is-
{"Id":1,"service_name":"asdf","service_charge":11.32,"service_type":null,"service_comission":14.65,"service_desc":"","after_service_charge":23.55,"service_duration":60,"after_service_comission":11.22,"service_frequency":58,"tax_rate":15}
Condition-
In my form- #form-service-values I have input field of same name as it comes in response. Now I wanted to fetch value from JSON where data name matches.
For ex-
data.service_name logs me with value asdf
But Now here It is coming to me when name is dynamic of input fields as-
[object Object].service_name
Here Is how I am handling it in ajax-
function getDescService(Idservice) {
$.ajax({
url: '/Service/GetServiceDescriptions/',
type: 'post',
data: { Id: Idservice },
success: function (data) {
$('#form-service-values input[type="text"]').each(function () {
var name = $(this).attr('name');
$(this).val(data + "." + name);
})
}
});
}
I am trying to get this JSON response in a form where name of inputs are same as it comes in JSON response.
I just want to access JSON data fields.
How do I try on it?

In javascript, an object can be access like that data.name, where name is the key, or like that data["name"]
So you should do this
$(this).val(data[name]);
Instead of this
$(this).val(data + "." + name);
The first one is retrieving the value stored at the key name in the object data, while the second one is only writing text.

Related

pushing javascript $.get response into variable

how can I push the data I get from https://somelink.com into a variable that I can display?
--> for example, the response is in this format {"ABC":1435.21}
e.g. I want to display "The value of ABC is 1435.21"
The response you are getting is JSON data, you can use that data like this
$.get( "https://somelink.com", function( data ) {
//Get first key of JSON object as String
let name = Object.keys(data)[0];
//Get value by key name
let value = data[name];
//Output
console.log("The value of "+name+" is "+value);
alert("The value of "+name+" is "+value);
}, "json" );
The last parameter of $.get() tells that we will be receiving JSON formatted data from server.

Parsing string of array of array of string back to array

I have an array of arrays of strings saved in a database column as a varchar:
[["ben"],["john","mike"],["ben"]]
I want to parse the data back into an array of arrays, so I can show the data on the screen. While attempting to do this, I ran into an awkward and annoying problem:
Here's the JSON response that is generated on the server and sent back to the client:
var response = "[{\"Names\":\""+ rows[i].Names + "\"}]";
res.send(response);
Here's the client code I wrote to parse the data:
jQuery.ajax({
type: "GET",
url: ...,
dataType: 'json',
contentType: "application/json; charset=utf-8"
}).done(function(data) {
jQuery.each(JSON.parse(data), function(i, parsedData) {
var names = JSON.parse(parsedData.Names);
var labels = "";
for (var n = 0; n < names.length; n++) {
var label = "<label>" + names[n] + "</label>";
labels = labels + label;
}
console.log(labels);
});
});
This is the error i'm getting:
Here's the JSON validation:
How can I solve this?
There is a simple rule:
Never use string tools to create or modify JSON. No string concatenation (+), no string replace and God forbid no regex.
The only way to produce JSON is to use a JSON serializer on a data structure. And the only way to manipulate JSON is to parse it, modify the data structure, and then serialize it again. JSON itself is to be treated as a constant, for all intents and purposes.
Your server code violates that rule. Change it like this:
var responseData = [{
Names: rows[i].Names
}];
var response = JSON.stringify(responseData);
In the above, responseData is a data structure. You are free to modify it. response is derived from that. You are not free to modify it, the only thing you can do with response is to write it to the client.
Note that rows[i].Names might be JSON itself, so you end up with a double-encoded value in your response.
Provided the server sends the Content-Type: application/json header, the client can use this:
jQuery.get("...").done(function(data) {
// data is already parsed here, you don't need to parse it
jQuery.each(data, function(i, item) {
// item.Names is not yet (!) parsed here, so we need to parse it
var names = JSON.parse(item.Names);
var labels = names.map(function (name) {
return $("<label>", {text: name});
}
console.log( labels );
});
});
If you don't want to call JSON.parse() on the client, you have to call it on the server:
var responseData = [{
Names: JSON.parse(rows[i].Names)
}];
var response = JSON.stringify(responseData);

How can i get value?

How can I extract value from response?
Output of alert is [{"maturitydays":"120"}]
I only want value!!
$("#selectCrop").change(function(){ //this ajax will bring default configured crop data
var cropid = $("#selectCrop option:selected").val();
var url = "<?php echo base_url();?>index.php/user/cropConfig/getData";
$.ajax({
data : {'cropid':cropid},
type : 'post',
url : url,
success :function(response) {
alert(response);
}
})
});
It appears your response is inside an array due to the square brackets, this means you need to get the value through:
response[0]['maturitydays']
So your code will look like:
$("#selectCrop").change(function(){ //this ajax will bring default configured crop data
var cropid = $("#selectCrop option:selected").val();
var url = "<?php echo base_url();?>index.php/user/cropConfig/getData";
$.ajax({
data : {'cropid':cropid},
type : 'post',
url : url,
success :function(response) {
alert(response[0]['maturitydays']);
}
})
});
It's json.
Use json_decode to make it array then grab the value from the array (if you must).
$array = json_decode('{"maturitydays":"120"}',true);
$value=$array["maturitydays"];
Echo $value;
https://3v4l.org/Uc51m
The data that you get as response is a JSON array with a number of JSON objects. JSON (JavaScript object notation) can be used as a JavaScript object right away (as long as its not in string form, in which case it has to be parsed with JSON.parse).
When you receive the response you can access it as you would with a normal JavaScript array (in case you are sure its ALWAYS only 1 object, you can select the first index right away):
let obj = response[0];
When you got the object, just access the value you want as you would with a normal JavaScript object:
let val = obj.maturitydays;

Pass Dictionary<String,List<String>> to java script

I would like to pass a Dictionary> to client using JavaScript.
I did look at this post and I didn't understand exactly how to proceed.
In case I'm doing something wrong I'll explain what I want to do.
The dictionary contains the 'name' key of all worksheets in the Excel file, and the 'value' is the column value of the first row in that worksheet.
The UI of the client should have two "drop list", the first will contain the key which is all the names of the worksheet in the Excel file.
The second contain all the column value of the first row of the worksheets that will choose in the first drop list – which is actually a List as the value in the dictionary.
So all the back end C# code is working fine. Now I need help in the front end JavaScript.
How do I parse the data to a key value so I can do a "search" on the keys as the client chooses some "key" in the first drop list so I can get back the relevant values as a list?
Thanx!
var ajaxRequest = $.ajax({
type: "POST",
url: "http://localhost:1894/api/Values",
contentType: false,
processData: false,
data: data,
success: function(dataTest) {
}
});
This is the JSON that I get back from the server:
{"First":["Name","Link","User","Pass"],"Sec":["test01"]}
How would I perform a search on this like in C#? I want to be able to do something like this: "dict.TryGetValue(key, out value); and the out value would return as an array of string or as a List.
Try this(you don't need var ajaxRequest variable you can directly call like this:
$.ajax({
type: "POST",
url: "http://localhost:1894/api/Values",
dataType: "json",
data: data,
success: function(dataTest) {
//dataTest should contain your data in a javascript object
for(var i = 0; i < dataTest.First.length; i++)
{
window.alert("" + dataTest.First[i]);
}
for(var i = 0; i < dataTest.Sec.length; i++)
{
window.alert("" + dataTest.Sec[i]);
}
//etc...
//this should print the values returned if you showed me exactly how your JSON is...
}
});
The javascript object will contain properties with an array as the value for each property. Think of it like a map of <String, String[]>. So your returned object dataTest will have properties First and Sec and for First the value associated with the key First will be ["Name","Link","User","Pass"] which is just an array. Same for Sec. So `dataTest.First[0] will equal "Name" and dataTest.First[1] will equal "Link" etc...
*****************************************UPDATE**************************************
You can save your dataTest to a global variable in this example (myObject) then you can access like this:
var key = "First";
// Or if you want to get your key from a dropdown (select) element then you could do like this:
var key = document.getElementById("myselect").options[document.getElementById("myselect").selectedIndex].innerHTML;
if(myObject[key] != undefined)
{
//That means there is values for this key.
//Loop through values or do whatever you want with myObject[key].
for(var i = 0; i < myObject[key].length; i++)
{
window.alert("" + myObject[key][i]);
}
}

json result display first value

I have found several posts similar to this topic but nothing I have tried has actually worked. My question is simple and should be easy to answer. My return json object will have one key and one value. For my code below, the alert shows "[{"DISCOUNT":1}]" and all I am trying to do is parse out the "1" and display it. Ultimately, I want to plug that value into a variable and use for multiplication, but I can't even get the darn number to display by itself. My code is below:
function codeMatchTest() {
if ($('#dbReturnString').val() == '') {
alert("Please enter a discount code.");
} else {
$.ajax({
type: "POST",
url: "PROMO.svc/MatchCode",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
success: function (json) {
alert(json.d);
/*alert (json.d.discount); // getting "undefined"
$.each(json.d, function (key, value) {
var discount = value;
});
alert("Success: " + discount); //getting "undefined" */
},
error: function () {
alert("There was an error with your request.");
}
});
}
}
I have found no good references on how to actually use the data in a json object. My json object will only consist of a single key and value and I will only ever need to use the value.
Also, I have tried several iteration using $.each and none work. Based on the jquery documentation, it should be very easy but I am having not luck.
If your alert is showing "[{"DISCOUNT":1}]" that means you have an object within an array.
try alert(json.d[0].DISCOUNT);
JSON parsed objects are case sensivetive, plus its seems that json.d contains a string (wich seems to be in json) rather than an object. Try:
var discount = JSON.parse(json.d);
discount = discount[0].DISCOUNT;
success: function(json) {
alert(json.d[0]["DISCOUNT"]);
}
First comment on your code, you are reinventing what jQuery does.
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
It should just be
data: { codeInput: $('#dbReturnString').val().toLowerCase() },
Now to get the data it is simple, you are returning an array with an object in it.
Let us look at it as a regular variable and not an Ajaqx call.
var json = [{"DISCOUNT":1}];
So you got an array? How do you get the object inside of it? You reference the index. Since you said there will only be one index being returned, than use [0] to access it.
success: function (json) {
alert(json[0].DISCOUNT);
To access the first item from the json you may use
alert(json.d[0].DISCOUNT);
Because json.d is an array and it contains one object which is 0 index. So, json.d[0] will select the first item/object from the array and using .DISCOUNT you can access the object's property. It's also possible to access the property like
alert(json.d[0]["DISCOUNT"]);
Try this way
You can use JSON.parse(json.d) / json.d
var data = json.d;
for(i=0;i<data.length;i++) {
alert(data[i].fieldname);
}

Categories