Javascript how to parse JSON array - javascript

I'm using Sencha Touch (ExtJS) to get a JSON message from the server. The message I receive is this one :
{
"success": true,
"counters": [
{
"counter_name": "dsd",
"counter_type": "sds",
"counter_unit": "sds"
},
{
"counter_name": "gdg",
"counter_type": "dfd",
"counter_unit": "ds"
},
{
"counter_name": "sdsData",
"counter_type": "sds",
"counter_unit": " dd "
},
{
"counter_name": "Stoc final",
"counter_type": "number ",
"counter_unit": "litri "
},
{
"counter_name": "Consum GPL",
"counter_type": "number ",
"counter_unit": "litri "
},
{
"counter_name": "sdg",
"counter_type": "dfg",
"counter_unit": "gfgd"
},
{
"counter_name": "dfgd",
"counter_type": "fgf",
"counter_unit": "liggtggggri "
},
{
"counter_name": "fgd",
"counter_type": "dfg",
"counter_unit": "kwfgf "
},
{
"counter_name": "dfg",
"counter_type": "dfg",
"counter_unit": "dg"
},
{
"counter_name": "gd",
"counter_type": "dfg",
"counter_unit": "dfg"
}
]
}
My problem is that I can't parse this JSON object so that i can use each of the counter objects.
I'm trying to acomplish that like this :
var jsonData = Ext.util.JSON.decode(myMessage);
for (var counter in jsonData.counters) {
console.log(counter.counter_name);
}
What am i doing wrong ?
Thank you!

Javascript has a built in JSON parse for strings, which I think is what you have:
var myObject = JSON.parse("my json string");
to use this with your example would be:
var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}
Here is a working example
EDIT: There is a mistake in your use of for loop (I missed this on my first read, credit to #Evert for the spot). using a for-in loop will set the var to be the property name of the current loop, not the actual data. See my updated loop above for correct usage
IMPORTANT: the JSON.parse method wont work in old old browsers - so if you plan to make your website available through some sort of time bending internet connection, this could be a problem! If you really are interested though, here is a support chart (which ticks all my boxes).

In a for-in-loop the running variable holds the property name, not the property value.
for (var counter in jsonData.counters) {
console.log(jsonData.counters[counter].counter_name);
}
But as counters is an Array, you have to use a normal for-loop:
for (var i=0; i<jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}

This is my answer:
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br>
Last Name: <span id="lname"></span><br>
</p>
<script>
var txt =
'{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
var counter = jsonData.employees[i];
//console.log(counter.counter_name);
alert(counter.firstName);
}
</script>
</body>
</html>

Just as a heads up...
var data = JSON.parse(responseBody);
has been deprecated.
Postman Learning Center now suggests
var jsonData = pm.response.json();

Something more to the point for me..
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
document.write(contact.phone[1]);
// Output:
// Aaberg, Jesper
// 555-0100
Reference:
https://learn.microsoft.com/en-us/scripting/javascript/reference/json-parse-function-javascript

"Sencha way" for interacting with server data is setting up an Ext.data.Store proxied by a Ext.data.proxy.Proxy (in this case Ext.data.proxy.Ajax) furnished with a Ext.data.reader.Json (for JSON-encoded data, there are other readers available as well). For writing data back to the server there's a Ext.data.writer.Writers of several kinds.
Here's an example of a setup like that:
var store = Ext.create('Ext.data.Store', {
fields: [
'counter_name',
'counter_type',
'counter_unit'
],
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'json',
idProperty: 'counter_name',
rootProperty: 'counters'
}
}
});
data1.json in this example (also available in this fiddle) contains your data verbatim. idProperty: 'counter_name' is probably optional in this case but usually points at primary key attribute. rootProperty: 'counters' specifies which property contains array of data items.
With a store setup this way you can re-read data from the server by calling store.load(). You can also wire the store to any Sencha Touch appropriate UI components like grids, lists or forms.

This works like charm!
So I edited the code as per my requirement. And here are the changes:
It will save the id number from the response into the environment variable.
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.data.length; i++)
{
var counter = jsonData.data[i];
postman.setEnvironmentVariable("schID", counter.id);
}

The answer with the higher vote has a mistake. when I used it I find out it in line 3 :
var counter = jsonData.counters[i];
I changed it to :
var counter = jsonData[i].counters;
and it worked for me.
There is a difference to the other answers in line 3:
var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
var counter = jsonData[i].counters;
console.log(counter.counter_name);
}

You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.
There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.
By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.

Not sure if my data matched exactly but I had an array of arrays of JSON objects, that got exported from jQuery FormBuilder when using pages.
Hopefully my answer can help anyone who stumbles onto this question looking for an answer to a problem similar to what I had.
The data looked somewhat like this:
var allData =
[
[
{
"type":"text",
"label":"Text Field"
},
{
"type":"text",
"label":"Text Field"
}
],
[
{
"type":"text",
"label":"Text Field"
},
{
"type":"text",
"label":"Text Field"
}
]
]
What I did to parse this was to simply do the following:
JSON.parse("["+allData.toString()+"]")

Related

Defining variables for JS lp-solver using an array

I'm trying to create a linear programing code in JS using lp-solver library, but I can't get the results to be outputted. It's probably because of incorrect model, because the results output for each product and "total cost" shows as undefined, so I'm guessing that the model doesn't work at all. The problem is that I'm not just inputting the variables by myself, but I fetch the products from a database (that is working correctly and I can output, for example, the first product's name as data[0]['name'] and it works just fine) so they are written in an array. I made a for loop trying to input the data of products into variables of the model, but I guess that is not working correctly or the problem is somewhere else in the model. May you please help me?
Part of code:
<script>
// Make an AJAX request to the PHP script that fetches the products and user's desired
calories from the database
$.ajax({
url: 'fetchProductsFromDatabase.php',
success: function(response) {
var data = response;
var userCalories = data[0]['userCalories'];
// Set up the model
var model = {
optimize: "price",
opType: "min",
constraints: {
"calories": {
equal: userCalories
},
},
variables: {
},
};
// Set up the variables and the constraints in the model
for (var i = 0; i < data.length; i++) {
model.variables[data[i]['name']] = { "price": data[i]['price'], "calories": data[i]
['calories'] };
model.constraints[data[i]['name']] = { equal: 0 };
}
// Solve the linear program
var result = solver.Solve(model);
Proof of "data" output. Written as console.log(data[0]['name/price/calories']);
Results of the code.
for (var i = 0; i < data.length; i++) {
console.log(data[i]['name'] + ': ' + result[data[i]['name']]);
}
console.log('Total cost: ' + result.price);

How to access variables inside an array

So, I have been trying to solve this all of yesterday and today but cannot figure it out. I have the following returned in a variable called
var myRequest = req.body
console.log(myRequest)
Produces the following:
{
"methodcall": {
"methodname": ["userLogin"],
"params": [{
"param": [{
"value": [{
"string": ["test1"]
}]
}, {
"value": [{
"string": ["password"]
}]
}]
}]
}
}
Now, I need to access the params key, and access the first param value so that whatever is returned in the first param value string is stored as username in a variable, and whatever is returned in param value string (the second one), is stored as a password.
So the final effect something like this:
var username = myRequest.methodcall.params.param...first value string
var password = myRequest.methodcall.params.param...second value string
However, I am really struggling to understand how to do this. Im guessing forEach loops would come in this, however I do not have experience with them so would appreciate some tips.
Also, when I try doing myRequest.methodcall, I keep getting undefined returned.
Any help will be greatly appreciated!
It sounds like your value is in JSON, parse it first and then you should presumably be able to get its values:
var myRequest = JSON.parse(req.body);
var userName = myRequest.methodcall.params[0].param[0].value[0].string[0];
var password = myRequest.methodcall.params[0].param[1].value[0].string[0];
What you have posted is JSON. you need to set it up like:
var myRequest = JSON.parse(req.body)
this will allow you to access the it like a normal js object.
Use . to access keys in object and [] to access index in array.
This code should work:
var username = myRequest.methodcall.params[0].param[0].value[0].string[0]
If you would like to use a loop at get the values test1,password, and so on. You can use a loop and access the param array:
var params = myRequest.methodcall.params[0].param;
params.forEach(function(item){
console.log(item.value[0].string[0]);
});
Fiddle
//var myRequest = JSON.parse(req.body) // if JSON
var myRequest = {
"methodcall": {
"methodname": ["userLogin"],
"params": [{
"param": [{
"value": [{
"string": ["test1"]
}]
}, {
"value": [{
"string": ["password"]
}]
}]
}]
}
};
var params = myRequest.methodcall.params;
var uname, pwd;
for (var i = 0; i < params.length; i++) {
console.log("uname is " + params[i].param[0].value[0].string);
console.log("pwd is " + params[i].param[1].value[0].string)
}
if your response structure will be same then no need to go for loop or something, just directly access the username and password from response.
try this.
var username = myRequest.methodcall.params[0].param[0].value[0].string[0];
var password = myRequest.methodcall.params[0].param[1].value[0].string[0];
Did you debug your code?
I mean these code:
var username = myRequest.methodcall.params.param[0];
var password = myRequest.methodcall.params.param[1];

Displaying nested JSON using JQUERY

I currently have a live search box that displays json. However I am having issues in working out how to display the nested JSON.
I am looking to display the images and the "closed" days. Any help would be appreciated. I have include my java-script and a sample of my json.
$('#search').keyup(function() {
var searchTerm = $(this).val();
var myExp = new RegExp(searchTerm, "i");
$.get("shops.php",function(data,status){
var response='';
var json = $.parseJSON(data);
shops = json.shops;
$.each(shops, function(index, item) {
if(item.shop_name.search(myExp) != -1){
response += "<h2>"+item.shop_name+"</h2>";
response += "<h2>"+item.distance_citycentre.driving_miles+"</h2>";
});
}
$("#content").html(response);
});
});
Here is a sample of my JSON.
{"shops": [
{ "shop_name":"tesco",
"distance_citycentre": {
"driving_miles":"1.5",
"driving_minutes":"3"
},
"closed": [
"monday",
"wedensday",
"friday"
],
"images" [
{
"description":"lake",
"id":"1"
},
{
"description":"ocean",
"id":"2"
}
]
},
{"shop_name":"asda", etc.......
Here goes your solution
$(document).ready(function() {
var data = '{ "shops":[{"closed":["monday","wedensday","friday"],"images" :[{"description":"lake","id":"1"},{"description":"ocean","id":"2"}]}]}';
var response='';
var json = $.parseJSON(data);
shops = json.shops;
alert(shops[0].closed[0] + " - "+shops[0].closed[1] + " - " +shops[0].closed[2]);
alert(shops[0].images[0].description + " - "+shops[0].images[0].id);
});
And change the JSON Output if possible, There is a little error near "image"<<-- It requires colon ":" You can find the same working model on [JSfiddle][1]
[1]: https://jsfiddle.net/u6exgn7s/ here
If you're talking about how to access json objects in an array which is in an array, you can access them by using array[0].object.array[0].object.array[0].array[0]
In your example you can select closed day 'monday' by using:
item.shops[0].closed[0];
or friday by using:
item.shops[0].closed[2];
You determine the position in the array by [-number from 0 to infinity-]

Getting json data from a nested array

I'm having a bit of trouble wrapping my head around some JSON stuff. Namely, I'm trying to retrieve a string from a json response received from the google translate api i'm querying.
var translator = function () {
for (var i = 0; i < result.length; i++)
{
//Construct URI
var source =
'https://www.googleapis.com/language/translate/v2?' +
'key=MY-API-KEY-REMOVED-ON-PURPOSE&' +
'source=en&' +
'target=fr&' +
'q=' +
result[i][1]; //looping over an array, no problem there
//Receive response from server
var to_Translate =new XMLHttpRequest();
to_Translate.open("GET",source,false);
to_Translate.send();
var translated = to_Translate.responseText;
JSON.parse(translated);
translated = translated.data.translations[0].translatedText;
console.log(translated);
}
};
translator();
Where
console.log(translated);
yields
{
"data": {
"translations": [
{
"translatedText": "some stuff that's been translated"
}
]
}
}
My question is: how can i access the value of translatedText? I've tried:
translated.data.translations[0].translatedText;
But it doesn't seem to work. When I console.log this i get
Uncaught TypeError: Cannot read property 'translations' of undefined
translator
(anonymous function)
Let me know what you guys think!
That is just text you have to parse it with
JSON.parse(translated)
so you could access it with, for example, translated.data
UPDATE
The error you are getting means that translated.data is undefined, you have to assign the parse to a variable, otherwise it will never work, it doesn't modify it in place
var translated = JSON.parse(to_Translate.responseText);
Yes, Use
translated.data.translations[0].translatedText;
Hope it will work fine.
So close!
translated.data.translations[0].translatedText;
translations is an array of objects, and you want the translatedText property of the first element in the array.
UPDATE:
Just to confirm the output of to_Translate.responseText is a string containing:
{
"data": {
"translations": [
{
"translatedText": "some stuff that's been translated"
}
]
}
}
So you should be able to do:
var translated = to_Translate.responseText,
parsed = JSON.parse(translated),
text = parsed.data.translations[0].translatedText;
console.log(text);

displaying json data in javascript not working

I have created a var and passed JSON data(comma seperated values) to it, but when I want to display json data - it only returns null. Here's the code:
<script type="text/javascript">
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
document.write(data1);
</script>
You can either do it like this:
var data1 = [{order:"145",country:"Dubai",employee:"permanent",customer:"self"} ];
data1.forEach(function(data){
document.write(data.order);
document.write(data.country);
document.write(data.employee);
document.write(data.customer);
});
or you can do it like this
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
$.each(data1[0], function(key, value){
document.write(key + " " + value);
});
Either way, storing just one object in the list makes this answer a bit redundant unless I show you how to loop over multiple objects.
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
data1.forEach(function(data){
$.each(data, function(key, value){
document.write(key+" "+value);
});
});
I'm using a mix of jQuery here aswell, which might not be optimal but atleast it serves to show that there are multiple ways to accomplishing what you need.
Also, the forEach() method on arrays is a MDN developed method so it might not be crossbrowser compliant, just a heads up!
If you want pure JS this is one of the ways to go
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
for(json in data1){
for(objs in data1[json]){
document.write(objs + " : " + data1[json][objs]);
}
}
For simple and quick printing of JSON, one can do something like below and pretty much same goes for objects as well;
var json = {
"title" : "something",
"status" : true,
"socialMedia": [{
"facebook": 'http://facebook.com/something'
}, {
"twitter": 'http://twitter.com/something'
}, {
"flickr": 'http://flickr.com/something'
}, {
"youtube": 'http://youtube.com/something'
}]
};
and now to print on screen, a simple for in loop is enough, but please not e, it won't print array instead will print [object Object]. for simplicity of answer, i won't go in deep to print arrays key and value in screen.
Hope that this will be usefull for someone. Cheers!
for(var i in json) {
document.writeln('<strong>' + i + '</strong>' +json[i] + '<br>');
console.log(i + ' ' + json[i])
}

Categories

Resources