Can not parse JSON with JavaScript parser. Square brackets - javascript

I using JavaScript JSON library to parse JSON encoded array, received via POST.
Here is my code:
var itemsRequest = '[{"id":"142"},{"id":"152"}]';
var items = JSON.parse(itemsRequest);
for(var i = 0; i<items.count(); i++)
{
var item = items[i];
alert(item.id);
}
I am not sure why, but the parser is just not liking that. How can I get it to parse?

Try items.length instead of items.count().

An array doesn't have a count method. Use the length property:
for (var i = 0; i < items.length; i++) {
Demo: http://jsfiddle.net/Guffa/Rt4db/

Below is the very good way to do:
var itemsRequest = '[{"id":"142"},{"id":"152"}]';
var items = eval(itemsRequest); //Converted to actual JSON data
for (var item in items) {
alert(items[item]['id']);
}
Hope this is very helpful, thanks

Related

Parse Json array push javascript

I have Json Parse list which need to push each category list.
example :
listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = [];
var values = [];
for(var i=0;i<listChartPeriods.length;i++){
categoryData.push(listChartPeriods.slice(0,1)[0]); //here need to push each date
values.push(listChartPeriods[i])
}
expected out put:
categoryData=["2018-05-04","2018-05-11","2018-05-18","2018-05-25","2018-06-01"]
values=[21807210.5028442,21807210.5028442,21807210.5028442]//each category values
Just use Object.keys to get the dates in the array.
const listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = Object.keys(listChartPeriods);
console.log(categoryData);
Below should get the job done for you. A for in loop is your friend when it comes to working with objects.
var listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = [];
for(var char in listChartPeriods){
for(var i = 0; i < listChartPeriods[char].length; i++){
categoryData.push(listChartPeriods[char][i]);
}
}
console.log(categoryData);
EDIT: Just read your updated question and you are only wanting the key names. You can also do this with a for in loop.
for(var char in listChartPeriods){
categoryData.push(char)
}
console.log(categoryData);
Following the solution:
for (let date in listChartPeriods){
categoryData.push(date);
let [first] = listChartPeriods[date];
values.push(first);
}
categoryData = ["2018-05-04", "2018-05-11", "2018-05-18", "2018-05-25", "2018-06-01"]
values = [21807210.5028442, 21807210.5028442, 21807210.5028442, 21807210.5028442, 21807210.5028442]

How to iterate over a json array

I used the Gson library to create a json from java and it returns me something like that:
[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]
How can I parse and access to the values in my js file?
i use a lot w3schools site here
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
Getting these is actually pretty easy in JS because JSON Objects are just considered Objects by js.
You can do this like so:
for (let i = 0; i < myArray.length; i++) {
let currObj = myArray[i];
let keys = Object.keys(currObj);
for (let j = 0; j < keys.length; j++) {
let myValue = keys[j];
doSomethingWithMyValue(myValue);
}
}
That will get every value for every key in every object in your array. This should give you a pretty good baseline for how these objects work.
Edit: Worth noting, there is also a Object.values(obj), method, which will return a list of all the values in your object in order, but it currently has very poor browser support, so you are much safer using Object.keys and then iterating over the keys like I showed above.
It's hard to say what you want to do with the data, and whether or not there are duplicate titles, as in your example. However...
var a = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
a.forEach(function(v) {
doSomething(v.title, v.author);
});
should work
With a for loop
If you get the JSON as an array
var json = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
If you get the JSON as a string
var string = '[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]';
var json = JSON.parse(string);
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
//Here an example ---
var elements=[{id:123, name:'lorem'},{id:456, name:'ipsum'},{id:998, name:'verrugas'}];
for (item in elements){
console.log(elements[item].name);
}
Ok, that was a very noob question.
Firstly, to access to the values I have to do something like
data.title
In my case I had an array so I had to use something like
var j = JSON.parse(data);
for (var i = 0; i < j.length ; i++) {
console.log(j[i].title);
}
When I run for the first time this function it said "JSon unexpected identifier Object, that because Gson was returning already a json and javascript was trying to create a json of a json, so I removed the JSON.parse(data) and now it works!
Thanks u all

Accessing ViewBag list via Javascript

I'm trying to access the elements of a list stored in ViewBag as follows:
function equipamentoTemControle() {
for(i = 0; i < #ViewBag.qtdEquipamentos; i++) {
var contratocod = #ViewBag.DadosEquipamentos[i].contratocod;
}
}
But when trying to access contratocod of attribute index i the Visual Studio says that the variable i does not exist. How do I access ?
Use
var jsonObj = #Html.Raw(Json.Encode(ViewBag.qtdEquipamentos));
and then
for (i = 0; i < jsonObj .length; i++) {
var contratocod = jsonObj[i].contratocod;
}
Hope this work first encode model in a JSON and then iterate.

How to parse read json elements with jquery

I have to create cart system in my mobile application, i want to store the id and the quantity of products, the id should be the key of my array (for modifying product quantity) , tried to use object instead of array but i get error: undefined is not a function when i try to read my json variable
by JSON.stringify(cart)
My cart code is like this
var cart = [];
var produit = {};
produit['qte'] = $('.'+id_prd).text();
produit['id_produit'] = id_prd;
cart[id_prd] = produit;
window.sessionStorage["cart1"]= JSON.stringify(cart);
return me
{"7":{"qte":"1","id_produit":7},"8":{"qte":"1","id_produit":8}}
when I tried to parse the json string with
var parsed = $.parseJSON(window.sessionStorage["cart1"]);
i get the error 'undefined is not a function'
when triying to read the json with
var i=0;
for (k in parsed) {
var k_data = parsed[k];
k_data.forEach(function(entry) {
alert(entry);
ch+=entry.id_produit;
if(i<parsed.length-1)
ch+= ',';
if(i==parsed.length-1)
ch+=')';
i++;
});
}
Can you clarify me the error cause, and if there's a solution to better read the json
The problem is that you are using k_data.forEach(function(entry) but forEach is for Arrays, and k_data is just a simple javascript object.
Try changing:
k_data.forEach(function(entry){
to this:
$(k_data).each(function(entry){
Even more, if the JSON is always in the same structure you posted, I think the each function is not necessary, maybe this is the way you are looking for:
var i=0;
var ch = "(";
for (k in parsed) {
var k_data = parsed[k];
alert(k_data);
ch+=k_data.id_produit;
ch+= ',';
i++;
}
ch = ch.substring(0, ch.length - 1) + ")";
You shouldn't need jQuery for this. The same JSON object you used to stringify has a parse function:
var parsed = JSON.parse(window.sessionStorage["cart1"]);
If that still breaks, there's probably something wrong with another undefined object.
You can try something like this:
<script type="text/javascript">
var finalArr = new Array();
var dataArr = new Array();
dataArr = window.sessionStorage["cart1"];
if (JSON.parse(dataArr).length > 0) {
for (var i = 0; i < JSON.parse(dataArr).length; i++) {
finalArr.push((JSON.parse(dataArr))[i]);
}
}
</script>

How to "clean" an array in javascript?

I am stuck here. How can I clean this array:
{"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
So that it looks like:
["5201521d42","52049e2591","52951699w4"]
I am using Javascript.
You just need to iterate over the existing data array and pull out each id value and put it into a new "clean" array like this:
var raw = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean = [];
for (var i = 0, len = raw.data.length; i < len; i++) {
clean.push(raw.data[i].id);
}
Overwriting the same object
var o = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for (var i = o.data.length; i--; ){
o.data[i] = o.data[i].id;
}
What you're doing is replacing the existing object with the value of its id property.
If you can use ES5 and performance is not critical, i would recommend this:
Edit:
Looking at this jsperf testcase, map vs manual for is about 7-10 times slower, which actually isn't that much considering that this is already in the area of millions of operations per second. So under the paradigma of avoiding prematurely optimizations, this is a lot cleaner and the way forward.
var dump = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var ids = dump.data.map(function (v) { return v.id; });
Otherwise:
var data = dump.data;
var ids = [];
for (var i = 0; i < data.length; i++) {
ids.push(data[i].id);
}
Do something like:
var cleanedArray = [];
for(var i=0; i<data.length; i++) {
cleanedArray.push(data[i].id);
}
data = cleanedArray;
Take a look at this fiddle. I think this is what you're looking for
oldObj={"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
oldObj = oldObj.data;
myArray = [];
for (var key in oldObj) {
var obj = oldObj[key];
for (var prop in obj) {
myArray.push(obj[prop]);
}
}
console.log(myArray)
Use Array.prototype.map there is fallback code defined in this documentation page that will define the function if your user's browser is missing it.
var data = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean_array = [];
for( var i in data.data )
{
for( var j in data.data[i] )
{
clean_array.push( data.data[i][j] )
}
}
console.log( clean_array );
You are actually reducing dimension. or you may say you are extracting a single dimension from the qube. you may even say selecting a column from an array of objects. But the term clean doesn't match with your problem.
var list = [];
var raw = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for(var i=0; i < raw.data.length ; ++i){
list.push(raw.data[i].id);
}
Use the map function on your Array:
data.map(function(item) { return item.id; });
This will return:
["5201521d42", "52049e2591", "52951699w4"]
What is map? It's a method that creates a new array using the results of the provided function. Read all about it: map - MDN Docs
The simplest way to clean any ARRAY in javascript
its using a loop for over the data or manually, like this:
let data = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},
{"id":"52951699w4"}]};
let n = [data.data[0].id,data.data[1].id, data.data[2].id];
console.log(n)
output:
(3) ["5201521d42", "52049e2591", "52951699w4"]
Easy and a clean way to do this.
oldArr = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
oldArr = oldArr["data"].map(element => element.id)
Output: ['5201521d42', '52049e2591', '52951699w4']

Categories