Im very new to JSON. I already tried the basics of JSON but in the examples Im using it is in array and the key is in string. Mine is quite different, its an object and the key is a number. Example of my JSON object is var ojbJSON = {55: 3, 23: 2};. My problems are I cannot get the length for an object because it doesn't have an attribute length and if I do something like alert(objJSON.55); to get the value 3 it causes a javascript error. Please don't ask why I'm insisting on this. Please help. Thanks.
You have to iterate to get the count:
var i=0;
for (var key in objJSON) i++;
alert(i);
You'd probably want to write a helper for this, something like:
function getLength(obj) {
var i=0;
for (var key in objJSON) i++;
return i;
}
alert(getLength(objJSON));
To get a key when it isn't a valid Javascript variable name (like numbers, or names that include hyphens, etc), you can use the bracket notation:
alert(objJSON[55]);
Related
When I run the below code in my react-native project
console.log("Response= "+JSON.stringify(response));
I can get output like below in my console.
Response= {"assets":[{"height":3888,"uri":"file:///data/user/0/com.facebook2/cache/rn_image_picker_lib_temp_6b8db334-4fcc-40ba-94a0-325191a89011.jpg","width":5184,"fileName":"rn_image_picker_lib_temp_6b8db334-4fcc-40ba-94a0-325191a89011.jpg","type":"image/jpeg","fileSize":1914937}]}
How I print the 'uri' from that JSON response ?
Looking at your data we can break it down by what we see. So, with JSON we have a Javascript Object which contains a param of assets. So to print assets we would console.log(response.assets)
Assets is an array with one item, so we want to get the first item from that which would be console.log(response.assets[0]).
Then we want the uri from that first assets object which would be console.log(response.assets[0].uri)
Hope this is what you are looking for.
You can use Dot Notation to access the properties of an object.
In your response json, it is seen that it has an array with name assets. The required property uri is inside the array. You can access it simply by
response.assets[0].uri
if there were multiple items in your assets array, you can simply loop over the array and get the values,
const length = response.assets.length;
for(let i=0; i< length; i++)
console.log('URI is = ', response.assets[i].uri)
const response = {"assets":[{"height":3888,"uri":"file:///data/user/0/com.facebook2/cache/rn_image_picker_lib_temp_6b8db334-4fcc-40ba-94a0-325191a89011.jpg","width":5184,"fileName":"rn_image_picker_lib_temp_6b8db334-4fcc-40ba-94a0-325191a89011.jpg","type":"image/jpeg","fileSize":1914937}]};
console.log('URI =', response.assets[0].uri)
I am trying to get a list of ID from a JSON file.
So far, the only way to access the "id" object is by using this:
console.log(photos.photosets.photoset[0].id);
As you might tell, it only gives me the correct ID of the first item.
If I try this, it gives me an "undefined":
console.log(photos.photosets.photoset.id);
No Angular, just JavaScript.
for (i = 0; i < photos.photosets.length; i++) {
console.log(photos.photosets.photoset[i].id
}
You will need to iterate array of photoset's and produce new array of ids from it. Array.prototype.map is convenient in this case:
var ids = photos.photosets.photoset.map(function(obj) {
return obj.id;
});
I often work with large JavaScript objects and instead of manually opening and closing "branches", I would like to simply search for a particular string and show any key or value that matches.
Sort of like "grepping" for a keyword in a JavaScript object. Is this possible (especially in Chrome Dev Tool)?
Unfortunately I was hoping I could at least try the JSON.stringify() trick and then search on the raw JSON in a text editor, but I get the following error:
Uncaught TypeError: Converting circular structure to JSON
You can look at the object's keys and match against them:
function grepKeys(o, query){
var ret = {};
Object.keys(o).filter(function(key){
return key.includes(query);
}).forEach(function(key){ // can reduce instead
ret[key] = o[key]; // copy over
});
return ret;
}
Which'd let you return a partial object with all the keys that contain the string you specified. Note that this will not show any prototype keys but can be easily extended to allow it (by using a for... in instead of an Object.keys or by using recursion):
var o = grepKeys({buzz:5, fuzz:3, foo:4}, "zz");
o; // Object {buzz: 5, fuzz: 3}
I am working on a WP8 app. In this I need to connect to web services whose results will be some JSON. I was trying to extract some data from the result that the web service provide. I was able to extract from the initial JSON response. But I need to get some data from the value of one such key . SO I tried to generate another Json object from it. But I m stuck. please help.Please find my example code below(I am using Newtonsoft.JSon).
private void messages_buttons_Click(object sender, RoutedEventArgs e)
{
var str = "{'status': '0', 'result': '%7B%22campaign_id%22%3A%221%22%2C%22tfn%22%3A%2218773374136%22%2C%22campaign_code%22%3A%22PJC%22%2C%22ad_id%22%3A%221%22%2C%22qr_url%22%3A%22http%3A%5C%2F%5C%2F1d1.us%5C%2FPJC%5C%2F%22%2C%22campaign_name%22%3A%22PJ+Test+Campaign%22%2C%22is_active%22%3A%221%22%2C%22expire_on%22%3A%222021-05-05+00%3A00%3A00%22%2C%22start_on%22%3A%222021-05-05+00%3A00%3A00%22%2C%22alias%22%3A%22%22%2C%22icon_image_url%22%3A%22products%5C%2Fpjc%5C%2Fpjc3.jpg%22%2C%22fb_page_url%22%3A%22https%3A%5C%2F%5C%2Fwww.facebook.com%5C%2FJackLaLannePowerJuicerssfb%22%2C%22video_url%22%3A%22http%3A%5C%2F%5C%2Fyoutube.com%5C%2Fembed%5C%2FyZPedpRA9r0%3Fshowinfo%3D0%26autoplay%3D1%26loop%3D1%26playlist%3DyZPedpRA9r0%22%2C%22url%22%3A%22https%3A%5C%2F%5C%2Fwww.facebook.com'}";
JObject ne = JObject.Parse(str);
var x= (ne.GetValue("result")).ToString();
var z = x.Replace("%", "");
JObject newest = JObject.Parse(z);
var y = newest.GetValue("campaign_id");
MessageBox.Show(y.ToString());
}
I get an exception at "JObject newest = JObject.Parse(z);" with the message
Unexpected character encountered while parsing number: m. Path '', line 1, position 6.
Am I doing it entirely wrong?
On a general note: can I convert a value from one Json to a another JSOn Itself? i.e if the value of one json key is a string with some key value pairs, can i make a json object on that string?
You can't actually just remove the % chars to get a valid value. You need to decode the string.
If you use this:
HttpUtility.UrlDecode(x);
You'll find your "result" is actually invalid JSON:
{"campaign_id":"1","tfn":"18773374136","campaign_code":"PJC","ad_id":"1","qr_url":"http://1d1.us/PJC/","campaign_name":"PJ
Test Campaign","is_active":"1","expire_on":"2021-05-05
00:00:00","start_on":"2021-05-05
00:00:00","alias":"","icon_image_url":"products/pjc/pjc3.jpg","fb_page_url":"https://www.facebook.com/JackLaLannePowerJuicerssfb","video_url":"http://youtube.com/embed/yZPedpRA9r0?showinfo=0&autoplay=1&loop=1&playlist=yZPedpRA9r0","url":"https://www.facebook.com
So hacking the value to make it valid JSON might work for you, by adding the missing "} at the end should turn your value in to valid JSON and allow you to parse it.
JObject newest = JObject.Parse(x + "\"}");
var y = newest.GetValue("campaign_id");
It doesn't appear that z is a valid json object at this point. It is only the value of result. Try something like JObject.Parse("'result':" + z);
I'm using jQuery templating which is taking JSON data to create a table. This code is working fine. But when I try to create a function around this code and pass JSON data to it which I'm getting from an AJAX request, it shows the values in the console but not in the table. Working code with dummy data is:
var json = [{"class":12,"marks":"500","marks1":"200","marks2":"300"},{"class":11,"marks":"200","marks1":"300","marks2":"400"}]
$.template('kList','<tr title="${class}"><td>${marks}</td><td>${marks1}</td><td>${marks2}</td></tr>');
for(var i=0; i<json.length; i++){
$.tmpl('kList',json[i]).appendTo("#table1")
}
Here is the code where I'm warping the upper code in function and passing the JSON data as a parameter that shows the values in console when I print it with console.log(json) but not filling the table. The JSON parameter is having the same JSON data as in above code.
function dataTable(json){
console.log(json); // here json values are appearing in the console
$.template('kList','<tr title="${class}"><td>${marks}</td><td>${marks1}</td><td>${marks2}</td></tr>');
for(var i=0; i<json.length; i++){
$.tmpl('kList',json[i]).appendTo("#table1")
}
}
Please help me out because I don't know whats wrong in this code. Thanks in advance.
Your json parameter is a string. You should convert it to an object, using $.parseJSON(json).
Take a look at this for conversion detail.