JS JSON process - javascript
I'm new in JSON handling, so I would like to get some help :)
I have this data in the data variable:
{"json":null,"id":"1111","prime1":"26","prime2":"0","ass1":"0","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"2111","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"3111","prime1":"11","prime2":"0","ass1":"0","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"4111","prime1":"4","prime2":"0","ass1":"17","ass2":"13","time1":"07:00:00","time2":"17:30:00"}*{"json":null,"id":"5111","prime1":"6","prime2":"0","ass1":"23","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"6111","prime1":"1","prime2":"0","ass1":"15","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"1112","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"2112","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"3112","prime1":"22","prime2":"0","ass1":"18","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"4112","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"5112","prime1":"3","prime2":"0","ass1":"19","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"6112","prime1":"9","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"1121","prime1":"3","prime2":"0","ass1":"15","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"2121","prime1":"6","prime2":"0","ass1":"23","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"3121","prime1":"11","prime2":"0","ass1":"0","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"4121","prime1":"8","prime2":"0","ass1":"17","ass2":"13","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"5121","prime1":"22","prime2":"0","ass1":"19","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"6121","prime1":"1","prime2":"0","ass1":"12","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"1122","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"2122","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"3122","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"4122","prime1":"8","prime2":"0","ass1":"13","ass2":"18","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"5122","prime1":"22","prime2":"0","ass1":"19","ass2":"0","time1":"14:00:00","time2":"21:30:00"}
I can't create objects from them.
This is my code:
var dataSplit = data.split("*");
for (var i = 0; i < dataSplit.length; i++) {
objects[i] = dataSplit[i];
document.getElementById("proba").innerHTML += objects[i].time2;
}
Thanks for all of you!
It's working now, it was 2 hours for me. The problem was I didn't initialize the object array and didn't use JSON.parse() (tried the JSON.parse() before, without success). So the solution is:
var objects = [];
var dataSplit = data.split("*");
for (var i = 0; i < dataSplit.length; i++) {
objects[i] = JSON.parse(dataSplit[i]);
document.getElementById("proba").innerHTML += objects[i].time2;
}
Related
Getting through all entries in JS by queryselector
I'm trying to get some informations from the page. If there is one entry I can do that by var z = document.querySelector('div.class').innerText; and then get it by +z somewhere where I need the value. But if there are more entries it will get only first. I'm trying to do sth like that to get them all: var x = document.querySelectorAll('div.class'); var i; for (i = 0; i < x.length; i++) { x[i].innerText; } But definitely something's wrong with this code. I'm not really familiar with JS, could you help me how to get all entries?
You can achieve that by using getElementsByClassName('class'). The script would be sort of: let list = document.getElementsByClassName('class'); for (let i = 0; i < list.length; i++) { console.log(list[i].innerText); } https://jsfiddle.net/esjcaqwb/
Your code looks ok, heres a working example that might be useful. var x = document.querySelectorAll('.example'); var r = document.querySelectorAll('.result') var i; for (i = 0; i < x.length; i++) { r.innerText += x[i].innerText; } What was going wrong with your code? In the example you provided, you're getting the value but not doing anything with it.
With your actual code you are not doing anything in the loop, the statement x[i].innerText; does nothing. If you want to get these elements contents in an array you can use: var results = Array.from(x).forEach(function(el){ return el.innerText; });
populate select element based on json
How could I populate a second select element? I've figured out how to do the first one. But how could I do the same for the second depending on which "Make" is selected? I've tried to talk myself through it while taking small steps but I'm thinking this may be too advanced for me. var cars = '{"USED":[{"name":"Acura","value":"20001","models":[{"name":"CL","value":"20773"},{"name":"ILX","value":"47843"},{"name":"ILX Hybrid","value":"48964"},{"name":"Integra","value":"21266"},{"name":"Legend","value":"21380"},{"name":"MDX","value":"21422"},{"name":"NSX","value":"21685"},{"name":"RDX","value":"21831"},{"name":"RL","value":"21782"},{"name":"RSX","value":"21784"},{"name":"SLX","value":"21879"},{"name":"TL","value":"22237"},{"name":"TSX","value":"22248"},{"name":"Vigor","value":"22362"},{"name":"ZDX","value":"32888"}]},{"name":"Alfa Romeo","value":"20047","models":[{"name":"164","value":"20325"},{"name":"8c Competizione","value":"34963"},{"name":"Spider","value":"22172"}]}'; var carobj = eval ("(" + cars + ")"); var select = document.getElementsByTagName('select')[0]; //print array elements out for (var i = 0; i < carobj.USED.length; i++) { var d = carobj.USED[i]; select.options.add(new Option(d.name, i)) };
If I read your question right, you want to populate a second select with the models for the make in the first select. See below for a purely JS approach (with jsfiddle). If possible, I would recommend looking into jQuery, since I would prefer a jQuery solution. http://jsfiddle.net/m5U8r/1/ var carobj; window.onload = function () { var cars = '{"USED":[{"name":"Acura","value":"20001","models":[{"name":"CL","value":"20773"},{"name":"ILX","value":"47843"},{"name":"ILX Hybrid","value":"48964"},{"name":"Integra","value":"21266"},{"name":"Legend","value":"21380"},{"name":"MDX","value":"21422"},{"name":"NSX","value":"21685"},{"name":"RDX","value":"21831"},{"name":"RL","value":"21782"},{"name":"RSX","value":"21784"},{"name":"SLX","value":"21879"},{"name":"TL","value":"22237"},{"name":"TSX","value":"22248"},{"name":"Vigor","value":"22362"},{"name":"ZDX","value":"32888"}]},{"name":"Alfa Romeo","value":"20047","models":[{"name":"164","value":"20325"},{"name":"8c Competizione","value":"34963"}, {"name":"Spider","value":"22172"}]}]}'; carobj = eval ("(" + cars + ")"); var makes = document.getElementById('make'); for (var i = 0; i < carobj.USED.length; i++) { var d = carobj.USED[i]; makes.options.add(new Option(d.name, i)); } makes.onchange = getModels; getModels(); } // add models based on make function getModels () { var makes = document.getElementById('make'); var make = makes.options[makes.selectedIndex].text; for (var i = 0; i < carobj.USED.length; i++) { if (carobj.USED[i].name == make) { var models = document.getElementById('model'); models.options.length = 0; for (var j= 0; j < carobj.USED[i].models.length; j++) { var model = carobj.USED[i].models[j]; models.options.add(new Option(model.name, j)); } break; } } } I would also recommend looking into safer JSON parsing. There is a security risk in using eval if it runs on any user input. You could look into JSON.org and their json2.js. Or if you want to use jQuery: parseJSON. Below is the jQuery version: jQuery.parseJSON(jsonString); JSON parsing tips from: Safely turning a JSON string into an object.
How do I split this string with Js?
i been reading for hours trying to make this work but i dont have much knowledge to do it. I have this js code: var username=$(this).attr("username"); It pull a list of users f.e (admin, test1, test2, test3) and i needs to split it into another var like this: var members = [ ['admin'], ['test1'], ['test2'], ['test3'], ]; I tried a lot of codes but i cant make it work, thanks in advance!
To get an array of usernames: var username = $(this).attr("username"); var members = username.split(','); To get exactly what you've suggested you want (an array of arrays? - I don't think this is actually what you want): var username = $(this).attr("username"); var membersArr = username.split(','); var members = new Array(); for (var i = 0; i < membersArr.length; i++) { members[i] = [ membersArr[i] ]; } To get "[test1]", "[test2]" etc: var username = $(this).attr("username"); var members = username.split(','); for (var i = 0; i < members.length; i++) { members[i] = '[' + members[i] + ']'; }
Update To get the array of arrays, var username=$(this).attr("username"); var membersArray= username.split(' ').map(function(username){ return [username]; }) //[["admin"],["test"],["test1"],["test2"]] I've added a fiddle here
Finding an object and returning it based on search criteria
I have been searching online all day and I cant seem to find my answer. (and I know that there must be a way to do this in javascript). Basically, I want to be able to search through an array of objects and return the object that has the information I need. Example: Each time someone connects to a server: var new_client = new client_connection_info(client_connect.id, client_connect.remoteAddress, 1); function client_connection_info ( socket_id, ip_address, client_status) { this.socket_id=socket_id; this.ip_address=ip_address; this.client_status=client_status; // 0 = offline 1 = online }; Now, I want to be able to search for "client_connection.id" or "ip_address", and bring up that object and be able to use it. Example: var results = SomeFunction(ip_address, object_to_search); print_to_screen(results.socket_id); I am new to javascript, and this would help me dearly!
Sounds like you simply want a selector method, assuming I understood your problem correctly: function where(array, predicate) { var matches = []; for(var j = 0; j < array.length; j++) if(predicate(j)) matches.push(j); return matches; } Then you could simply call it like so: var sample = []; for(var j = 0; j < 10; j++) sample.push(j); var evenNumbers = where(sample, function(elem) { return elem % 2 == 0; }); If you wanted to find a specific item: var specificguy = 6; var sixNumber = where(sample, function(elem) { return elem == specificguy; });
What have you tried? Have you looked into converting the data from JSON and looking it up as you would in a dictionary? (in case you don't know, that would look like object['ip_address']) jQuery has a function for this jQuery.parseJSON(object).
You're going to need to loop through your array, and stop when you find the object you want. var arr = [new_client, new_client2, new_client3]; // array of objects var found; // variable to store the found object var search = '127.0.0.1'; // what we are looking for for(var i = 0, len = arr.length; i < len; i++){ // loop through array var x = arr[i]; // get current object if(x.ip_address === search){ // does this object contain what we want? found = x; // store the object break; // stop looping, we've found it } }
loop with array data
i have this code to get three values. success: function(json){ $msg1 = parseFloat(json[0].valor1); $msg2 = parseFloat(json[1].valor2); $msg3 = parseFloat(json[2].valor3); } but now suppose that i need 200 values. I'm not doing 200 times ... $msg1 = parseFloat(json[0].valor1); $msg2 = parseFloat(json[1].valor2); $msg3 = parseFloat(json[2].valor3); //... $msg200 = parseFloat(json[199].valor200); so, i need a loop, correct? i tried something like this for (i=0; i<200; i++) { $msg(i+1) = parseFloat(json[i].valor(i+1)); i++; } but didn't work thanks
This is why The Creator gave the world arrays. var msgs = []; for (var i = 0; i < 200; ++i) msgs.push(parseFloat(json[i]['valor' + i])); Note that your JSON data should also keep those "valor" properties as arrays, though in JavaScript you can deal with a bizarre naming scheme like that as in the example above. edit — oops, typos fixed :-)
$msg = []; for (var i=0; i<200; i++) { $msg.push(parseFloat(json[i]["valor"+i])); }
As stated by Pointy or: var msgs = []; for (i=0; i<200; i++) { $msg[i] = parseFloat(eval('json[' + i + '].valor(' + i + '+1)')); i++; } However eval is slow, so Pointy's answer is better.
var array = json.someid;// or json['someid']; // json is returned not an array var msgs = []; $.each(array, function(index, e) { msgs.push(parseFloat[e['valor' + index], 10); }); when using parseFloat use the radix parameter unless you want bad things to happen; javascript needs to be told for example not to parse octal;