Printing JSON properties - javascript

I am currently trying to send a user information about a JSON object that I've recieved from an API. An example of the format is
[
{
"lang_code": "eng",
"site_language": "1",
"name": "English"
},
{
"lang_code": "afr",
"site_language": "1",
"name": "Afrikaans"
},
{
"lang_code": "ale",
"site_language": "0",
"name": "Aleut"
},
]
I want to be able to access the lang_code property of every single language and send it. I've tried to use
var languageCodes;
var languageResult = body.lang_code; //body is the result from a request.get({ ... })
for(var codes in languageResult) {
languageCodes = languageResult[codes];
}
Object.keys does nothing, as it just sends 72 numbers to me. Any thoughts?
On a side note, I also want people to be able to type "! languages [my command] eng", for example, and it sends "English" instead of just sending "1 is [object Object]".

Assuming body is the array at the top of your question, if you just want an array of all the language codes, this should suffice
var languageCodes = body.map(function(lang) {
return lang.lang_code;
});
var body = [{
"lang_code": "eng",
"site_language": "1",
"name": "English"
}, {
"lang_code": "afr",
"site_language": "1",
"name": "Afrikaans"
}, {
"lang_code": "ale",
"site_language": "0",
"name": "Aleut"
}];
var languageCodes = body.map(function(lang) {
return lang.lang_code;
});
document.getElementById('out').innerHTML = JSON.stringify(languageCodes);
<pre id="out"></pre>

I looped through your lang_codes like this:
var codes = [{"lang_code":"eng","site_language":"1","name":"English"}, {"lang_code":"afr","site_language":"1","name":"Afrikaans"},{"lang_code":"ale","site_language":"0","name":"Aleut"}];
for(var i = 0; i < codes.length; i++) {
console.log(codes[i].lang_code);
}

Related

Postman: Wanted to validate data values getting from API in JSON format

I wanted to check some combinations of validations for values I am getting from API request in postmanlike
if "tracked": "Yes" then analytics > "transitTime": 239 should be present.
The snippet of API response:
{
"status": 200,
"data": [{
"id": 107267,
"branchId": "22",
"status": "1",
"googleETA": "2018-02-01 20:44:51",
"runDate": "2018-01-29",
"runOfTheDay": "1",
"ATD": "2018-01-29 14:02",
"simCarrier": "Vodafone",
"pingStatus": "Ok",
"driverName": "test",
"shipperCompanyId": "007",
"ETA": "2018-01-30 12:31:00",
"locationSource": "sim",
"created_at": "2018-01-29 07:05:54",
"updated_at": "2018-01-29 12:35:40",
"tracked": "Yes",
"analytics": {
"loadingTime": 55.62,
"unloadingTime": 0,
"transitTime": 239
},
"trackingStatusAtClosure": {
"Origin": "No",
"Transit": "No",
"Destination": "No"
}
}]
}
This is a very basic check and I would advise against using it anywhere other than practising in a local environment.
pm.test("Basic Check", () => {
var jsonData = pm.response.json().data
for(i = 0; i < jsonData.length; i++) {
if(jsonData[i].tracked === 'Yes') {
pm.expect(jsonData[i].analytics.transitTime).to.not.be.null
} else {
console.log('Tracked does not equal Yes')
}
}
})
As your data only has one item in the data array you don't really need to add the for loop but I added it in for you so you can see that the same check would run if you have more than one item. If the tracked property is 'Yes' then the test is checking if analytics.transitTime not null. Like I said, its a basic check and it's not doing a great deal but hopefully that will give you the information you need to get started.

get string of elements by name

I'm newbee in JS so i need your help.
I have this JSON code :
{
"data": {
"people": [
"get_my_obj": [
{
"yearcome": 2006,
"email": "email1#test.com",
"came": "1.12",
"name": "Alex "
},
{
"yearcome": 2010,
"email": "email2#test.com",
"came": "1.12",
"name": "John"
},
{
"yearcome": 2012,
"email": "email3#test.com",
"came": "1.12",
"name": "Max"
}
]
}
}
How i can get string of elements with emails?
For example var a = email1#test.com;email2#test.com;email3#test.com;
Thats really hard for me because if i have only 2 objects so string must show 2 emails if 3 objects show 3 emails.
Please help me find the way how to do it
var s = { data: ....};
var mails = s.data.people.get_my_obj.map(function (e) { return e.email; }).join(';');
console.log(mails);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Reading JSON data for a particular ID

I have some JSON data which is in the following format:
[
{
"id": 145,
"Name": "John",
"company_name": "A",
"email": "john#gmail.com",
"country": "USA"
},
{
"id": 500,
"Name": "Mike",
"company_name": "B",
"email": "mike#gmail.com",
"country": "London"
},
{
"id": 100,
"Name": "Sally",
"company_name": "C",
"email": "sally#gmail.com",
"country": "USA"
}
]
Now, suppose I ask the user to enter an id, say 100. Then I need to display all the details for this id.
I am supposed to do this as a part of a web application,where I have to invoke an display the fields of a particular id. This would have been easy if I had a hash like implementation and could display all parameters based on the key-id.
Can anybody tell me how this can be done using such kind of data?
Thanks!
You could use something like this:
(Assuming the you have a variable data with your Json Object).
function getid(id) {
var nobj;
data.forEach(function(obj) {
if(obj.id == id)
nobj = obj;
});
return nobj
}
var neededobj = getid(100);
console.log(neededobj.Name + "\n" + neededobj.email + "\netc...");
But to get the Object you have to loop through your complete array,
until it finds the right Object
see this Fiddle
I think you are looking for Associative Array,
the simplex one would be,
var associativeArray = [];
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
alert(associativeArray.one);
And obviusly you can add json object in value place

How to create JSON using Javascript with sets of data?

I know that I can create this JSON:
[
{
"Title": "Something",
"Price": "234",
"Product_Type": "dsf sf"
},
{
"Title": "hskiuea",
"Price": "4234",
"Product_Type": "sdawer"
}
]
*It uses the values obtained from text inputs contained within an element with the class "newpappend" - As shown below
Using the following code which obtains values from my HTML:
var jsonObj = []; //declare array
$(".newpappened").each(function () {
var p_title = $(this).find('#p_title').val();
var p_price = $(this).find('#p_price').val();
var p_ptype = $(this).find('#p_ptype').val();
jsonObj.push({Title: p_title, Price: p_price, Product_Type: p_ptype});
$(this).remove();
});
But, my goal is to end up with the JSON structured like this:
{
"Product_List": {
"Product": [
{
"Title": "asdf",
"Price": "53",
"Product_Type": "Adfsdf"
},
{
"Title": "asgsd",
"Price": "123",
"Product_Type": "Ntohig"
}
]
}
}
Basically, I am struggling with the correct Javascript to use to reach my goal
You are really close. Start with what you have, and then later:
var output = {
"Product_List": {
"Product": jsonObj
}
}
// output is now what you are looking for.

problem parsing JSON Strings

var records = JSON.parse(JsonString);
for(var x=0;x<records.result.length;x++)
{
var record = records.result[x];
ht_text+="<b><p>"+(x+1)+" "
+record.EMPID+" "
+record.LOCNAME+" "
+record.DEPTNAME+" "
+record.CUSTNAME
+"<br/><br/><div class='slide'>"
+record.REPORT
+"</div></p></b><br/>";
}
The above code works fine when the JsonString contains an array of entities but fails for single entity. result is not identified as an array!
Whats wrong with it?
http://pastebin.com/hgyWw5hd
result is not an array. Do you see any square brackets in your JSON? no you do not. it does not contain any arrays.
{
"result": {
"ID": "30",
"EMPID": "1210308550",
"CUSTID": "1003",
"STATUS": "2",
"DATEREPORTED": "1273234502",
"REPORT": "this is one more report!",
"NAME": "Sandeep Savarla",
"CUSTNAME": "Collateral",
"LOCID": "4",
"LOCNAME": "Vijayawada",
"DEPTNAME": "SALES"
}
}
Can you show me what your "valid" json looks like when the function above works?
Just make sure it's an array before you iterate
if ( 'undefined' == typeof records.result.length )
{
records.result = [records.result];
}
Your code is looping through records.result as if it were an array.
Since it isn't an array, your code does not work.
This simplest solution is to force it into an array, like this:
var array = 'length' in records.result ? records.result : [ records.result ];
for(var x = 0; x < array.length; x++) {
var record = array[x];
...
In your code result is an object, not an array. Wrap it's value in square brackets to make it an array:
{
"result": [{
"ID": "30",
"EMPID": "1210308550",
"CUSTID": "1003",
"STATUS": "2",
"DATEREPORTED": "1273234502",
"REPORT": "this is one more report!",
"NAME": "Sandeep Savarla",
"CUSTNAME": "Collateral",
"LOCID": "4",
"LOCNAME": "Vijayawada",
"DEPTNAME": "SALES"
}]
}

Categories