Beginner JavaScript: Working with JSON and Objects in JavaScript - javascript

I have some JSON returned to the browser like this "product":
{ "Title": "School Bag", "Image": "/images/school-bag.jpg" }
I want this data to be a "Product" object so I can use prototype methods like a toHTMLImage() that returns a HTML image representation of the product:
function Product() { }
Product.prototype.toHTMLImage = function() { //Returns something like <img src="<Image>" alt="<Title>" /> }
How do I convert my JSON results into a Product object so that I can use toHTMLImage?

Simple, if I got it,
var json = { "Title": "School Bag", "Image": "/images/school-bag.jpg" }
function Product(json) {
this.img = document.createElement('img');
this.img.alt = json.Title;
this.img.src = json.Image;
this.toHTMLImage = function() {
return this.img;
}
}
var obj = new Product(json); // this is your object =D

var stuff = { "Title": "School Bag", "Image": "/images/school-bag.jpg" }
var newstuff = new Product();
for(i in stuff) newstuff.i = stuff[i];
Not sure if this will work, but give it a shot:
var stuff = { "Title": "School Bag", "Image": "/images/school-bag.jpg" }
stuff.prototype = Product;

Maybe this page will be usefull : http://www.json.org/js.html

For converting JSON to an object you can use
window.JSON.parse(jsonText) in Mozilla (check Chrome and Opera, I don't know how it works there.)
In Internet Explorer you can use (new Function("return " + jsonText))(),
but you should check the JSON for non-valid symbols, google it.

Related

Extract objects from object in JSON using JavaScript

So, I have access to a JSON-file and I'm supposed to list a few items in a neat fashion. The JSON-file is however written in a way I'm not familiar with. I have the following code:
function readFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if (rawFile.readyState === 4 && rawFile.status === 200)
{
window.openedFile = JSON.parse(rawFile.responseText);
console.log(JSON.stringify(openedFile, undefined, 4));
createList();
}
};
rawFile.send();
}
function createList() {
var table = document.createElement('table');
var body = document.createElement('tbody');
for (var i = 0; i < openedFile.sites.length; i++) {
var item = document.createElement('tr');
var colSite = document.createElement('td');
colSite.appendChild(document.createTextNode(openedFile.sites[i].name));
item.appendChild(colSite);
body.appendChild(item);
}
table.appendChild(body);
document.getElementById('list').appendChild(table);
}
..and it does not work as it claims the array "sites" is empty. The result from the JSON-file in the output in the console gives (with slight modifications in the variable names):
{
"sites": {
"1007": {
"id": 1007,
"name": "Location B",
"devices": {
"p3": {
"name": "p3",
"version": "5"
}
}
},
"1337": {
"id": 1337,
"name": "Location A",
"devices": {
"p2": {
"name": "p2",
"version": "5"
},
"p1": {
"name": "p1",
"version": "5"
}
}
}
},
}
If I change the JSON-file and add [] brackets after sites and remove "1007" and "1337" it looks like I'm used to (as an ordinary array), and it works. I'm pretty sure I'm not allowed to do this however and I get the same problem again when trying to extract information about the devices. I would appreciate any help on this matter. And to clarify, I'm trying to avoid changing the JSON-file, if there is some other solution.
The numerals 1007 and 1337 are properties of the object sites. Use a for-in loop to iterate through the object properties.
var sites = openedFile.sites;
for(var site in sites){
console.log("Key: ", site);
console.log("Value: ", sites[site]);
}
Sites is an object, not an array, so you need to iterate over the object's properties, not the elements of the array.
In order to get a list of those properties, you can use Object.keys(). That gives you an array of the property names.
Once you have that array, you iterate over it and each time use the current element, which is the name of the property of the original object.
For example, this works (just console logging the object name, the extraction you've already got):
function createList2() {
var len = Object.keys(openedFile.sites); //get array of property keys
for (var i of len) { //iterate over the array of property keys
console.log(openedFile.sites[i].name); /*retrieve properties by key from original object */
}
}

Creating Function to Parse JSON Data using substring

i'm working in AS2 & it's looks like javascript alot
JSON
{
"name": "Tom",
"age": 20,
"state": "usa"
}
now i cant parse JSON data in AS2 & need workaround function using substring
something like that below and i load json file using loadVars()
var _lv:LoadVars = new LoadVars()
_lv.onData = function(data)
{
var ex:Object = eval("data");
var JSONTOArray:Object = ex.toString().split(',');
var getname=JSONtoArray[0].substring(JSONtoArray[0].lastIndexOf('"name": "')+9,JSONtoArray[0].lastIndexOf('"'));
}
_lv.load("MyJSON_URL");
now need to build function like
getThis('name'); // return Tom
getThis('age'); // return 20
getThis('state'); // return usa
The best solution is to use existing parser, because
you will not have to write your own code
it probably has common syntax like JSON.parse and JSON.stringify
var abc={
"name": "Tom",
"age": 20,
"state": "usa"
};
console.log(abc['name']); //Tom
console.log(abc['age']); //20
console.log(abc['state']); //usa
To parse a json data using ActionScript 2, you can use the JSON.as class ( from JSON.org ), after putting it in the same directory as your .fla, you can use it like this :
import JSON;
var json = new JSON();
var loader:LoadVars = new LoadVars();
loader.onData = function(data)
{
trace(json.parse(data).name); // gives : Tom
}
loader.load('file.json');
Hope that can help.

Convert String to Array of JSON Objects (Node.js)

I'm using Node.js and express (3.x). I have to provide an API for a mac client and from a post request I extract the correct fields. (The use of request.param is mandatory) But the fields should be composed back together to JSON, instead of strings.
I got:
var obj = {
"title": request.param('title'),
"thumb": request.param('thumb'),
"items": request.param('items')
};
and request.param('items') contains an array of object but still as a string:
'[{"name":"this"},{"name":"that"}]'
I want to append it so it becomes:
var obj = {
"title": request.param('title'),
"thumb": request.param('thumb'),
"items": [{"name":"this"},{"name":"that"}]
};
Instead of
var obj = {
"title": request.param('title'),
"thumb": request.param('thumb'),
"items": "[{\"name\":\"this\"},{\"name\":\"that\"}]"
};
Anyone who can help me with this? JSON.parse doesn't parse an array of object, only valid JSON.
How about this:
var obj = JSON.parse("{\"items\":" + request.param('items') + "}");
obj.title = request.param('title');
obj.thumb = request.param('thumb');
JSON.stringify(obj);
Perhaps I'm missing something, but this works just fine:
> a = '[{"name":"this"},{"name":"that"}]';
'[{"name":"this"},{"name":"that"}]'
> JSON.parse(a)
[ { name: 'this' }, { name: 'that' } ]
Node#0.10.13
May be you have old library Prototype. As I remove it, bug has disappeared.
You can try the same code. Once in page with Prototype.js. Second time in new page without library.

jQuery object get value by key

How would you get the value of assocIMG by key matching the key eg
if I have a var 11786 I want it to return media/catalog/product/8795139_633.jpg
var spConfig = {
"attributes": {
"125": {
"id": "125",
"code": "pos_colours",
"label": "Colour",
"options": [{
"id": "236",
"label": "Dazzling Blue",
"price": "0",
"oldPrice": "0",
"products": ["11148"]
}, {
"id": "305",
"label": "Vintage Brown",
"price": "0",
"oldPrice": "0",
"products": ["11786", "11787", "11788", "11789", "11790", "11791", "11792", "11793"]
}]
}
}
};
var assocIMG = // Added - Removed { here, causes issues with other scripts when not working with a configurable product.
{
11786: 'media/catalog/product/8795139_633.jpg',
11787: 'media/catalog/product/8795139_633.jpg',
}
Above is the objects I am working with and below is my current jQuery. Help would be greatly appreciated.
$('#attribute125').change(function() {
var image = $(this).val();
$.each(spConfig.attributes, function() {
prods = $(this.options).filter( function() { return this.id == image; } )[0].products[0];
alert(prods);
});
});
You can use bracket notation to get object members by their keys. You have the variable prods containing a string ("11786"), and the object assocIMG with various keys. Then just use
assocIMG[prods]
to get the property value 'media/catalog/product/8795139_633.jpg' which is associated with that key.
Note that you should always use strings as keys in your object literal, IE does not support numbers there:
var assocIMG = {
"11786": 'media/catalog/product/8795139_633.jpg',
"11787": 'media/catalog/product/8795139_633.jpg'
};
Another improvement to your script would be not to loop through the spConfig.attributes each time, and potentially execute your action multiple times if an image is contained in more than one attribute. Instead, build a hash object out of it, where you can just look up the respective product id.
var productById = {};
$.each(spConfig.attributes, function() {
$.each(this.options, function() {
var id = this.id;
productsById[i] = this.products[0];
});
});
$('#attribute').change(function() {
var id = this.value;
var prod = productById[id];
var image = assocIMG[prod];
$("#product_img").attr("src", image);
});
You should not use numbers as object keys (in their start). If you want to get the value associated with the 11786 integer key, you will need to use this syntax:
assocIMG["11786"] or assocIMG[11786]
Not
assocIMG.11786
The first thing that you need to do is to create your keys as strings, since you would have:
var assocIMG = {
"11786": 'media/catalog/product/8795139_633.jpg',
"11787": 'media/catalog/product/8795139_633.jpg',
}
But even doing this, you won't be able to access the field using assocIMG.11786 and the first valid sintax that I presented will still work. The correct approach would be:
var assocIMG = {
id11786: 'media/catalog/product/8795139_633.jpg',
id11787: 'media/catalog/product/8795139_633.jpg',
}
Or
var assocIMG = {
"id11786": 'media/catalog/product/8795139_633.jpg',
"id11787": 'media/catalog/product/8795139_633.jpg',
}
Note that the keys are now starting with letters, not numbers. And now, you will can access the 11786 field as assocIMG.id11786 or assocIMG["id11786"], not assocIMG[id11786]
To Get the Value from object by matching key I ended up with the following
$.each(assocIMG, function(index, value) {
if(index == prods) {
var image_path = value;
$("#product_img").attr("src", image_path);
//alert(image_path);
}

Use a JSON array with objects with javascript

I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:
Variable that I will pass to the function will look like this:
[{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}]
function test(myJSON) {
// maybe parse my the JSON variable?
// and then I want to loop through it and access my IDs and my titles
}
Any suggestions how I can solve it?
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON
.
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
By 'JSON array containing objects' I guess you mean a string containing JSON?
If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.
After that you just iterate over the array as normal.
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i].Title);
}
Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:
if you have the JSON string as above then you'd just need to do this
var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');
then you can access these vars with something like jsonObj[0].id etc
Let me know if that's not what you were getting at and I'll try to help.
M
#Swapnil Godambe
It works for me if JSON.stringfy is removed.
That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td>No Id</td><td>Title</td></tr>");
for(var i=0;i<datas.length;i++){
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");
}
document.writeln("</table>");

Categories