Issue mapping Json string with ko.mapping - javascript

On the server side I have a Asp.Net Web application, a WebMethod returns a Json string serialized just like this one:
Object { d= "[{"Id":"1","Name":"COMERCIAL BANK"},
{"Id":"2","Name":"AZTEC BANK"},
{"Id":"3","Name":"EL SALVADOR BANK"}]" }
When I try mapping that result using var mappedBanks = ko.mapping.fromJSON(data.d), and then use console.log(mappedBanks) all I get printed is c() and is like that mappedBanks, that should be an array, has no elements because I can iterate on it and when I try to print the first element, the console says undefined. Is there a problem with the Json? or I´m not mapping it right.

ko.mapping.toJSON requires first argument to be an object, not an array. Your option is to make your JSON-encoded array to be property value.
var mappedBanks = ko.mapping.fromJS({ items: JSON.parse(data.d) });
console.log(mappedBanks.items);

Related

Json Keys Are Undefined When Using Them From Script Tag

I've been trying to load certain Json with Ajax GET request and then parsing it.
However when trying to access the Json key from HTML script tag it was undefined.
In order to debug this issue, I logged all the keys of Json in console as well as the Json itself. Therefore i utilized this function:
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, "); // Explanation is below
console.log(invList[0]) // Just testing with first object
console.log(Object.keys(invList[0]));
});
}
getInv();
Purpose of data.split(",, "):
Since my backend script uses different programming language, I had to interpret it to the one suitable for Javascript.
There also were multiple Json objects, So i separated them with ",, " and then split them in Javascript in order to create a list of Json objects.
After calling the function, Following output was present:
Although the interesting part is that after pasting Json object in console like this:
This was the output:
So basically, in script tag, i was unable to access object's keys, although once i used it manually in console, all keys could be accessed.
What could be the purpose behind this? It seems quite strange that different outputs are given. Perhaps invList[0] is not Json object at all in the script tag? Thanks!
data.split() returns an array of strings, not objects. You need to use JSON.parse() to parse the JSON string to the corresponding objects.
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, ");
console.log(invList[0]) // Just testing with first object
var obj = JSON.parse(invList[0]);
console.log(Object.keys(obj));
});
}
You can use .map() to parse all of them, then you'll get an array of objects like you were expecting:
var invList = data.split(",, ").map(JSON.parse);

Accessing Elements of JS Object

I have created array in a object,
var obj_report_dailog = { array_report_dailog : [] }
Then push data to object,
obj_report_dialog.array_report_dialog.push({from: fromDate})
obj_report_dialog.array_report_dialog.push({to: toDate})
obj_report_dialog.array_report_dialog.push({fabrika: fabrika})
Then,
var json = JSON.stringify(obj_report_dialog);
How can I access to elements of that object?
console.log("işte bu: " + json);
output:
işte bu: {"array_report_dialog":[{"from":"2017-08-01"},{"to":"2017-09-21"},{"fabrika":["Balçova"]}]}
Two things:
You don't want to JSON.stringify unless you're sending the resulting string somewhere that will parse it. Remember, JSON is a textual notation for data exchange; JSON.stringify gives you a string to send to some receiver. When you have the JSON string, you don't access the properties of the objects in it.
If you're receiving that JSON string, you'd parse it via JSON.parse and then access the properties on the result.
Leaving aside the JSON thing, you probably don't want to add data the way you're adding it. You're adding three separate objects as three entries in the array, each with one property. You probably want to push one object with all three properties:
obj_report_dialog.array_report_dialog.push({
from: fromDate,
to: toDate,
fabrika: fabrika
});
Then you'd access them as obj_report_dialog.array_report_dialog[0].from, obj_report_dialog.array_report_dialog[0].to, and obj_report_dialog.array_report_dialog[0].fabrika. Or more likely, you'd have a loop like this:
obj_report_dialog.array_report_dialog.forEach(function(entry) {
// Use entry.from, entry.to, and entry.fabrika here
});
(See this answer for more options for looping through arrays.)
But, if you really want to push them as separate objects, you'd access them as obj_report_dialog.array_report_dialog[0].from, obj_report_dialog.array_report_dialog[1].to, and obj_report_dialog.array_report_dialog[2].fabrika (note the indexes going up).
If you stringify a json, it's gonna create a string representation of your object.
To access data in a string like that we usually use JSON.parse that create an json object from a string. Which is the obj_report_dailog you had at start.
You can make object from json by using JSON.parse()
JSON.parse(json).array_report_dialog

Nan is being set in json model when trying to bind with odata response

I am creating a restructured json model in our sapui5 app wherein the data is being received from the odata response. I am using the json.setproperty() method.
if i try n access the value with following methods
var two = 2;
var test = "Count"
var three = test+two
alert(odata.results[0][three]);
correct value is being alerted with object notation as against Nan being alerted if dot notation was used.
so in a loop im trying to fill the content of the json
for(var i=0;i<=count-2;i++){
var z = "Count"+i;
countjson.setProperty("/data/data/"+i+"/Count",odata.results[0].z);
countjson.setProperty("/data/data/"+i+"/Count",odata.results[0][z]);
}
Nan is being returned when im trying with the dot notation and undefined is being returned with object notation.
if i hardcode the path i.e odata.results[0].Count4 i am getting the 4th element from the odata resp and getting set in all fields of the new json.
Please help me with the above.
Best regards
archit
You cannot access a multidimensional array like that. Instead try using this -
odata.results[0][odata.results[0].indexOf(three)]

How does JSON.parse() work?

I have not worked too much on javascript. And, I need to parse a JSON string. So, I want to know what exactly JSON.parse does. For example :
If I assign a json string to a variable like this,
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now when I print 'ab', I get an object.
Similarly when I do this :
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
var rs = JSON.parse(pq);
The 'rs' is the same object as 'ab'. So what is the difference in two approaches and what does JSON.parse did differently ?
This might be a silly question. But it would be helpful if anybody can explain this.
Thanks.
A Javascript object is a data type in Javascript - it's have property and value pair as you define in your first example.
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now What is Json : A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other)
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
so it's is a String With json Format.
and at last JSON.parse() Returns the Object corresponding to the given JSON text.
Here is my explanation with a jsfiddle.
//this is already a valid javascript object
//no need for you to use JSON.parse()
var obj1 = {"name":"abcd", "details":"1234"};
console.log(obj1);
//assume you want to pass a json* in your code with an ajax request
//you will receive a string formatted like a javascript object
var str1 = '{"name":"abcd", "details":"1234"}';
console.log(str1);
//in your code you probably want to treat it as an object
//so in order to do so you will use JSON.parse(), which will
//parse the string into a javascript object
var obj2 = JSON.parse(str1);
console.log(obj2);
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
Your 'ab' variable isn't a string, it is a proper javascript object, since you used the {} around it. If you encased the whole thing in "" then it would be a string and would print out as a single line.
Data Type!! That is the answer.
In this case, ab is an object while pq is a string (vaguely speaking). Print is just an operation that displays 'anything' as a string. However, you have to look at the two differently.
String itself is an object which has properties and methods associated with it. In this case, pq is like an object which has a value: {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}} and for example, it has a property called length whose value is 66.
But ab is an object and you can look at name and details as its properties.
What JSON.parse() did differently was that, it parsed (converted) that string into an object. Not all strings can be parsed into objects. Try passing {"name":"abc" and JSON.parse will throw an exception.
Before parsing, pq did not have any property name. If you did something like pq.name, it'll return you undefined. But when you parsed it using JSON.parse() then rs.name will return the string "abcd". But rs will not have the property length anymore because it is not a string. If you tried rs.length then you'll get a value undefined.

checking json value in javascript

var saurabhjson= JSON.stringify(data)
above returns this json
saurabhjson {"recordId":5555,"Key":"5656"}
if print the first array in console it get undefined value
console.log("saurabhjson[0].recordId",saurabhjson[0].recordId);
i want to do some check like this
if(saurabhjson[0].recordId == 5555) {
$('#div_ajaxResponse2').text("another success");
}
As the method suggests JSON.stringify(data). It converts a js object to a jsonstring now if you want a key out of this string it can't be done before parsing it to json.
So i don't get it why do you need to stringify it.
And another thing is you have a js object not an array of objects. so you need to use this on data itself:
console.log("data.recordId",data.recordId);
You are probably mixing a few things there.
When you do var saurabhjson= JSON.stringify(data), that saurabhjson variable is a string, not an object, so you can't access its elements like you are trying to do.
Try accessing data directly instead, without using JSON.stringify():
console.log("data.recordId",data.recordId);

Categories

Resources