Read Value of JSON Result in Jquery - javascript

Here is my output of WebMethod through Ajax call:
var item=""[{\"Column1\":\"false\"}]""
There is always one row output,i-e true or false,i want to get the value of Column1,i already try Jquery.ParseJson(item),but it gives Illegal Token o error,Kindly help me how to read this value.Kindly check the inverted commas,this is the exact outcome of my web method, and this outcome and format is a necessary condition of scenario.Thanks.On using loop it gives the error:

If I understand your problem correctly, I think your extra quotes around the strings are a problem, this is invalid syntax.
This works:
var item = "[{\"Column1\":\"false\"}]";
var parsed = JSON.parse(item);
parsed.forEach(function(row) {
console.log(row.Column1);
});
console.log(parsed[0].Column1);
Here is a jsfiddle.
See here about jQuery.ParseJson vs JSON.parse, I prefer JSON.parse, but either should work fine.
In the case of older browsers without forEach use a for loop or a library like underscore.
var item="[{\"Column1\":\"false\"}]";
var parsed = JSON.parse(item);
//if forEach is not supported:
for (var i = 0; i < parsed.length; i++) {
console.log(parsed[i].Column1);
}
console.log(parsed[0].Column1);
Here is a for loop jsfiddle.

I understand that above solutions not work perfectly with your browsers, here is another alternate solution, though I know that it may not fit your scenario, but as your output is either true or false .Instead of using JsonConvert on server end, simply return the object array to client end and read value like this.
var tempo=item[0].Column1;

Not sure about the output of your service but I think you could try this:
str = 'var item=""[{\"Column1\":\"false\"}]""';
str = str.replace(/"/g, '');//remove quotes and slashes to make valid json
eval(str);//evaluate the string
console.log(item[0].Column1);

Related

How do I access a JSON array in JavaScript

I have a PHP script to which I make an Ajax request, and most of it works okay, but I'm having trouble accessing an array in the data returned to the JavaScript function.
So, the PHP has a bunch of regular variables, and one array. The array, $places, has four elements, which each have three values, as so:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
A relevant excerpt of the PHP script is:
$encoded_places = json_encode($places); // if I don't do this then I end up with a value of "Array"
$qobject->name = "$name";
$qobject->multi = "$multi";
$qobject->places= "$encoded_places";
$myJSON = json_encode($qobject);
echo $myJSON;
In the JavaScript script (using JQuery), I successfully obtain the data from the Ajax request, and I can access all the data okay, except the $places data.
$.getJSON(url, function(data, status){
var stringified = JSON.stringify(data);
var parsedObj = JSON.parse(stringified);
var x = parsedObj.name; // alert(x); // which works fine
var myArray = new Array();
myArray.push(parsedObj.places);
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
}
... and the console will display what I'm expecting, namely:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
However, I'm having difficulty accessing these values. For example, supposing I try to access the "815" portion of the first element, with something like: myArray[0][1], all I end up with is "[".
I guess somehow this whole piece of data is just a string, instead of an array, but I'm not familiar enough with JavaScript to quite know how to progress.
If, for example, I do this in the JavaScript script (hoping to see 815, 2813, 1582 and 1220 in the alerts) all I'll see is the single alert with "[". (i.e. it does the loop only once, and selects the character in position 1).
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
alert(myArray[i][1]);
}
I would very much appreciate someone explaining:
(a) how I can access the individual elements and values in JS
(b) how I can loop through them, although presumably once it's an array and not a string then the code above should do this.
Many thanks for any assistance.
Now Resolved:
As noted by #charlietfl, below, using quotes in
$qobject->places= "$encoded_places";
screwed things up, along with using json_encode on $places. However, without removing the quotes nothing worked either way. So, removed quotes and just used json_encode on the entire structure at the end, which now works fine.
So, the original snippet of code, given above, now looks like:
$qobject->name = $name;
$qobject->multi = $multi;
$qobject->places= $places;
$myJSON = json_encode($qobject);
echo $myJSON;
Change
$qobject->places = "$encoded_places";
To
$qobject->places = $places;
And get rid of the $encoded_places = json_encode($places); so that the one call to json_encode serializes the whole structure
Try this:
$.getJSON(url, function(data, status){
var parsedObj = JSON.parse(stringified);
console.table(parsedObj.places);
console.log(parsedObj.places)[0][0];
}
In the posted code's getJSON context, data is already a JSON string. So this line is redundantly stringifying your JSON string:
var stringified = JSON.stringify(data);
stringified is now set to a literal/escaped version of the valid JSON string from the data parameter:
[[\"z\",\"815\",\"1\"],[\"w\",\"2813\",\"0\"],[\"s\",\"1582\",\"2\"],[\"b\",\"1220\",\"5\"]]
When that double-stringified value is passed to JSON.parse for the parsedObj reference, it just becomes the original JSON string again (which looks deceptively correct in an alert box).
Strings are iterable in JavaScript, so the for loop was just going over the string.

Using Jquery to get numeric value which is in between "/" in link

I am trying to fetch numeric value from link like this.
Example link
/produkt/114664/bergans-of-norway-airojohka-jakke-herre
So I need to fetch 114664.
I have used following jquery code
jQuery(document).ready(function($) {
var outputv = $('.-thumbnail a').map(function() {
return this.href.replace(/[^\d]/g, '');
}).get();
console.log( outputv );
});
https://jsfiddle.net/a2qL5oyp/1/
The issue I am facing is that in some cases I have urls like this
/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre
Here I have "3" inside text string, so in my code I am actually getting the output as "11466433" But I only need 114664
So is there any possibility i can get numeric values only after /produkt/ ?
If you know that the path structure of your link will always be like in your question, it's safe to do this:
var path = '/produkt/114664/bergans-of-norway-airojohka-jakke-herre';
var id = path.split('/')[2];
This splits the string up by '/' into an array, where you can easily reference your desired value from there.
If you want the numerical part after /produkt/ (without limitiation where that might be...) use a regular expression, match against the string:
var str = '/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre';
alert(str.match(/\/produkt\/(\d+)/)[1])
(Note: In the real code you need to make sure .match() returned a valid array before accessing [1])

Javascript Object not working with Native javascript methods like match(), replace etc

Here is the issue:
I go this Code:
var str = {"Acc":10 , "adm_data":"Denied"};
When I do something like:
console.log(str.Acc.match(/[0-9]+/g)) // To Get the Integer Value from the "Acc" key
Firebug Screams:
TypeError: str.Acc.match is not a function
console.log(str.Acc.match(/[0-9]+/g));
See Image:
I always do something like:
var str = "Hello _10";
console.log(str.match(/[0-9]+/g)) // This Works
Why is the Object thingi not working?
PLEASE NOTE:
As mentioned by #Fabrício Matté. The issue was that I was trying to
pass an integer Value to the .match method which does not belong
to integers. The solution was to do what #kundan Karn Suggested. Something like:
str.Acc.toString().match(/[0-9]+/g)// Converting it first to string then match. It worked!
match function works with string. So convert it to string first
str.Acc.toString().match(/[0-9]+/g)
It works just fine: http://jsfiddle.net/nKHLy/
but in order to get rid of the error you might want to try:
var str = {"Acc":"Hello_10" , "adm_data":"Denied"};
console.log(String(str.Acc).match(/[0-9]+/g));
or
var str = {"Acc":"Hello_10" , "adm_data":"Denied"};
console.log(str.Acc.toString().match(/[0-9]+/g));
To know the difference between the 2 options, check: What's the difference between String(value) vs value.toString()

How to escape JSON in an HTML string stored as a Javascript variable?

I'm trying to parse a JSON string and I can't get it to work because of illegal chracters - which I cannot find...
Here is what I have:
make = function (el) {
var config = el.getAttribute("data-config");
console.log(config);
var dyn = $.parseJSON(config)
console.log(dyn);
}
var a= document.createElement("Star Icon");
console.log(a);
make(a);
I'm not really sure how to correctly unescape the JSON in my original string "a", so that it works.
Question_:
Which quotation marks do I need to escape to get this to work?
Thanks!
EDIT:
Ok. I figured it out using Jquery (I'd prefer Javascript-only though). This works:
make = function (el) {
var config = el.attr("data-config");
console.log(config);
var dyn = $.parseJSON(config)
console.log(dyn);
}
var c = $('<a href="#" class="template" data-config=\'{"role":"button","iconpos":"left","icon":"star","corners":"false","shadow":"false", "iconshadow":"false", "theme":"a","class":"test", "href":"index.html","text":"Star Icon", "mini":"true", "inline":"true"}\'>Star Icon</a>')
console.log(c);
make(c);
So escaping the start/end quotations of the JSON string seems to do the trick. The actual problem was that I can not use document.createElement with a full string. I can only create the element document.createElement(a) and then set innerHTML. Need to look into this some more.
If someone can tell me a Javascript-only way how to do this, please let me know.
Thanks!
Strings and object keys in JSON must be double quoted. Double quotes in attributes are not valid, so you'll need to escape them with ".
Also, you probably want to use booleans true/false instead of strings "true"/"false".
var a = document.createElement('Star Icon');
Notice this is completely unreadable and #millimoose's suggestion about just setting the attribute afterwards will make this much easier to deal with in the long run.

How to access JSON.parsed object in javascript

I did JSON.parse and getting output in javascript variable "temp" in format like this
{"2222":{"MId":106607,
"Title":"VIDEOCON Semi Automatic Marine 6.8kg",
"Name":"washma01",
}}
I tried like
alert(temp[0][0]);
alert(temp.2222[0].MId);
but not getting output.
How will I access this data in javascript ?
alert(temp["2222"].MId);
You can't use numeric indexing, because don't have any actual arrays. You can use dot syntax if the first character of the key is non-numeric. E.g.:
var temp = JSON.parse('{"n2222":{"MId":106607, "Title":"VIDEOCON Semi Automatic Marine 6.8kg", "Name":"washma01", }}');
alert(temp.n2222.MId);
Try this:
temp["2222"].MId
Typically temp.bar and temp["bar"] are equivalent JavaScript statements, but in this case one of your property name starts with a number. When this happens you are forced to use the index (aka bracket) notation.
You need to access the variable like so temp['2222']['MId'] , That will give you the value of MId. Even though I have shown using the [] method of getting the value , the answers below work as well.
You can run this test below in firebug.
var ss = {"2222":{"MId":106607, "Title":"VIDEOCON Semi Automatic Marine 6.8kg", "Name":"washma01"}};
console.log(ss['2222']['MId']);
when you have a good json formated object, but you don't know the key (here it look like an id) you can acces like this :
var keys = Object.keys(json_obj);
for (var i = 0; i < keys.length; i++) {
console.log(keys[i]);
console.log(json_obj[keys[i]].MId);
};

Categories