How to loop through the response text of JSON file? - javascript

I have a JSON file that contains object like that:
{
"status": "ok",
"feed": {
},
"items": [
{
"title": "",
"author": ""
},
{
"title": "",
"author": ""
},
{
"title": "",
"author": ""
}
]
}
I want to loop through the items and get each item data like title and author.
The code I tried:
var json = $.getJSON({'url':"filejson" , 'async': false});
json = JSON.parse(json.responseText);
$.each(json, function(index , item) {
console.log(json[index]);
});

It would appear the sync version of it acts in a weird way,
var json = JSON.parse($.getJSON({'url':"filejson" , 'async': false}).responseText);
let items = json.items;
items.forEach(item=>{
console.log(item.title, item.author);
})
As a sidenote, you should really not be using async: false.

Object.keys(json).forEach(function(key) {
console.log(json[key])
})
// or if supported/polyfilled
Object.values(json).forEach(function(value) {
console.log(value)
})

Use map():
data.map(d => ({title: d.title, author: d.author}));

Please use the following code
var json = $.getJSON({'url':"filejson" , 'async': false});
json = JSON.parse(json.responseText);
$.each(json.items, function(key , value) {
console.log(value['title'] + " : "+ value['author']);
});

Related

Lodash compare/merge object to array

I need to compare/merge 2 objects with diferent structure using Lodash.
data= [
{
"name": "EMPRESA",
"value": ""
},
{
"name": "DESIGEMPRESA",
"value": "CMIP"
},
{
"name": "UTILIZADOR",
"value": ""
},
{
"name": "CD_INDICADOR",
"value": ""
},
{
"name": "DT_INI_INDICADOR",
"value": ""
},
{
"name": "DT_INI",
"value": "2017-12-13"
},
.....
]
and
dbcolsData={
"EMPRESA": "",
"UTILIZADOR": "paulo.figueiredo",
"CD_INDICADOR": "",
"DT_INI_INDICADOR": "",
"DT_INI": "",
"DT_FIM": ""
}
The question is how i can fill the values of data with the values of dbcolsData ?
Lets say put the values of dbColsData in data
Thanks in advance
Try something like this:
_.forEach(data, function(object){
object.value = dbcolsData[object.name];
})
Use Array#map (or lodash's _.map()) to iterate the data, and get the results from dbcolsData:
var data = [{"name":"EMPRESA","value":""},{"name":"DESIGEMPRESA","value":"CMIP"},{"name":"UTILIZADOR","value":""},{"name":"CD_INDICADOR","value":""},{"name":"DT_INI_INDICADOR","value":""},{"name":"DT_INI","value":"2017-12-13"}];
var dbcolsData = {"EMPRESA":"","UTILIZADOR":"paulo.figueiredo","CD_INDICADOR":"","DT_INI_INDICADOR":"","DT_INI":"","DT_FIM":""};
var result = data.map(function(o) {
return Object.assign({ data: dbcolsData[o.name] }, o);
});
console.log(result);
Reduce data to the dbcolsData structure :
var myData = data.reduce((o, nvO) => Object.defineProperty(o, nvO.name, {value: nvO.value}), {})
->
Now you can use lodash comparison functions like _.isEqual :
_.isEqual(myData, dbcolsData)

Deleting a key in JSON while making ajax call from javascript

I am new to java script and ajax. I have a JSON and I want to remove outputs cell in this JSON:
{
"cells": [{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "print(\"hi\")",
"execution_count": 1,
"outputs": [{
"output_type": "stream",
"text": "hi\n",
"name": "stdout"
}]
},
{
"metadata": {
"trusted": true,
"collapsed": true
},
"cell_type": "code",
"source": "",
"execution_count": null,
"outputs": []
}
],
"metadata": {
"kernelspec": {
"name": "Python [Root]",
"display_name": "Python [Root]",
"language": "python"
},
"anaconda-cloud": {},
"language_info": {
"pygments_lexer": "ipython3",
"version": "3.5.0",
"codemirror_mode": {
"version": 3,
"name": "ipython"
},
"mimetype": "text/x-python",
"file_extension": ".py",
"name": "python",
"nbconvert_exporter": "python"
},
"gist": {
"id": "",
"data": {
"description": "Untitled5.ipynb",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 0
}
and this is my attempt on removing the outputs cell. This piece of code posts the data to above mentioned JSON:
"use strict";
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
var outputs = data.cells;
var data_dup = _objectWithoutProperties(data, ["outputs"]);
var id_input = $('#gist_id');
var id = params.gist_it_personal_access_token !== '' ? id_input.val() : '';
var method = id ? 'PATCH' : 'POST';
// Create/edit the Gist
$.ajax({
url: 'https://api.github.com/gists' + (id ? '/' + id : ''),
type: method,
dataType: 'json',
data: JSON.stringify(data_dup),
beforeSend: add_auth_token,
success: gist_success,
error: gist_error,
complete: complete_callback
});
};
But this code doesnt work. Can some one please guide how can we directly strip a key(outputs in this case) from ajax call and post it to JSON.
This is a gist extension of jupyter notebook and I am trying to strip output while posting it to gist on github
function _objectWithoutProperties(obj, key="outputs") { obj.cells.forEach(cell=>delete(cell[key])); }
If you use ES6, you can use this syntax to remove outputs:
{
...data,
cells: data.cells.map(({ outputs, ...otherProps }) => otherProps),
}
Note: data is your complete object.

Create JSON from dynamic HTML form

Here is my fiddle: DEMO
I want my JSON to be as below on click of "Save Actions" and when the category is "SMS". I'm not able to achieve this.
Also, the form fields change on change of category.
{
"name": "",
"category": "SMS",
"description": "",
"apiUrl": "",
"apiMethod": "GET",
"apiPayload": {
"senderName": "",
"number": "",
"message": ""
},
"#class": "action"
}
Any help would be much appreciated. Thanks :)
Move the apiPayload out of the reduce callback function.
And assign the value after the reduce loop.
$('#saveActions').on('click', function(e) {
var apiPayload = {};
var jsonData = $('form.form-horizontal#events')
.find(':input:not(button):not(#new-option-event)').get()
.reduce(function(acc, ele) {
if (ele.closest('.payload')) {
var i = 0;
apiPayload[ele.name] = ele.value.trim();
} else {
acc[ele.name] = ele.value.trim();
}
return acc;
}, {});
jsonData['apiPayload'] = apiPayload;//assign value
jsonData['#class'] = "action";
alert(JSON.stringify(jsonData, null, 4));
});

JSON.parse returning error

So this is my JSON.stringify'd return before I try to run JSON.parse
{"id":"2","name":"<small>L</small>(+)-Amethopterin Hydrate","class":"6.1","subclass":"","packing_group":"III","un":"2811","cas":"133073-73-1","poisons":"","hazardous":"Yes","restricted":"No","epa":"","added_by":"0","carcinogen":null},
{"id":"3","name":"(+)-Biotin 4-Nitrophenyl ester","class":"","subclass":"","packing_group":"","un":"","cas":"33755-53-2","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null},
{"id":"4","name":"(+)-Biotin N-hydroxysuccinimide ester","class":"","subclass":"","packing_group":"","un":"","cas":"35013-72-0","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}
When I try to JSON.parse I get Unexpected end of JSON input. And I can't access it as a JSON object because it will say can't define id or something to that extent.
JSON.parse(this.searchService.searchJson(this.php_url));
this.searchService.searchJson(this.php_url) is basically what my JSON string is. Gives error as mentioned above.
Also if I just try to stringify 1 of the 3 elements, it'll give me Unexpected token u in JSON at position 0
Calling function:
searchJson(url: any): any
{
let items: any = [];
let new_data: any = [];
$.getJSON(url ,
function(data)
{
let temp_items: any = {};
console.log(data);
$.each(data, function (key, val)
{
new_data.push(JSON.stringify(val));
});
});
return new_data;
}
You have to wrap it with [] because that is an array of objects:
const data = [{"id":"2","name":"<small>L</small>(+)-Amethopterin Hydrate","class":"6.1","subclass":"","packing_group":"III","un":"2811","cas":"133073-73-1","poisons":"","hazardous":"Yes","restricted":"No","epa":"","added_by":"0","carcinogen":null}, {"id":"3","name":"(+)-Biotin 4-Nitrophenyl ester","class":"","subclass":"","packing_group":"","un":"","cas":"33755-53-2","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}, {"id":"4","name":"(+)-Biotin N-hydroxysuccinimide ester","class":"","subclass":"","packing_group":"","un":"","cas":"35013-72-0","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}]
console.log(data); will return [Object, Object, Object]
or if you wanna process as a JSON string you should do this:
const data = '[{"id":"2","name":"<small>L</small>(+)-Amethopterin Hydrate","class":"6.1","subclass":"","packing_group":"III","un":"2811","cas":"133073-73-1","poisons":"","hazardous":"Yes","restricted":"No","epa":"","added_by":"0","carcinogen":null}, {"id":"3","name":"(+)-Biotin 4-Nitrophenyl ester","class":"","subclass":"","packing_group":"","un":"","cas":"33755-53-2","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}, {"id":"4","name":"(+)-Biotin N-hydroxysuccinimide ester","class":"","subclass":"","packing_group":"","un":"","cas":"35013-72-0","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}]'
JSON.parse(data) will return too [Object, Object, Object]
Changed the calling function to this:
searchAjax(url: any): any
{
let new_data: any;
return $.ajax({
url: url,
type: 'post',
dataType: "json",
async: false
}).responseText;
}
The most likely cause was that my variable was that my variable was null at the time of being called because of async.
file Nmae: self.json
[
{
"id": "2",
"name": "<small>L</small>(+)-Amethopterin Hydrate",
"class": "6.1",
"subclass": "",
"packing_group": "III",
"un": "2811",
"cas": "133073-73-1",
"poisons": "",
"hazardous": "Yes",
"restricted": "No",
"epa": "",
"added_by": "0",
"carcinogen": null
},
{
"id": "3",
"name": "(+)-Biotin 4-Nitrophenyl ester",
"class": "",
"subclass": "",
"packing_group": "",
"un": "",
"cas": "33755-53-2",
"poisons": "",
"hazardous": "No",
"restricted": "No",
"epa": "",
"added_by": "0",
"carcinogen": null
},
{
"id": "4",
"name": "(+)-Biotin N-hydroxysuccinimide ester",
"class": "",
"subclass": "",
"packing_group": "",
"un": "",
"cas": "35013-72-0",
"poisons": "",
"hazardous": "No",
"restricted": "No",
"epa": "",
"added_by": "0",
"carcinogen": null
}
]
$(document).ready(function($) {
$.ajax({
url: 'self.json',
type: 'GET',
dataType: 'json',
})
.done(function(respose) {
for (var i = 0; i < respose.length; i++) {
resText = respose[i].id+' '+respose[i].name+' '+ respose[i].class+' '+respose[i].subclass;
console.log(resText);
};
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
Output:

Starting at a specific index in each function

Please take a look at this fiddle
How can I use slice in the loop to make it return results starting from a specific index?
The JSON file:
[
{
"title": "A",
"link": "google.com",
"image": "image.com",
"price": "$1295.00",
"brand": "ABC",
"color": "Black",
"material": "Rubber"
}
]
I want it to return results starting from brand:
brand - ABC
color - Black
material - Rubber
I don't know where to put .slice(4) in the loop. I got undefined error using
$.each(value.slice(4),function(key, value)
Here's the code:
JS:
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FaZgYDB%22&format=json&diagnostics=true&callback=",
success: function (data) {
var item_html="";
$(data.query.results.json).each(function(key, value) {
$.each(value,function(key, value){
item_html += '<h3>'+key+' - '+value+'</h3>';
});
});
$('#area').append(item_html);
}
});
Use a separate array of property names, so you can slice it and get the names in a guaranteed order.
var props = [
"title",
"link",
"image",
"price",
"brand",
"color",
"material"
];
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FaZgYDB%22&format=json&diagnostics=true&callback=",
dataType: 'json',
success: function (data) {
var item_html="";
var propslice = props.slice(4);
$.each(data.query.results.json, function(i, obj) {
$.each(propslice, function(i, key) {
value = obj[key];
item_html += '<h3>'+key+' - '+value+'</h3>';
});
});
$('#area').append(item_html);
}
});
If there are a small number of properties you want to skip, you can make a list of them in an object, and test against that list:
var excluded_props = {
title: true,
link: true,
image: true,
price: true
};
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FaZgYDB%22&format=json&diagnostics=true&callback=",
dataType: 'json',
success: function (data) {
var item_html="";
$.each(data.query.results.json, function(i, obj) {
$.each(obj, function(key, value) {
if (!excluded_props[key]) {
value = obj[key];
item_html += '<h3>'+key+' - '+value+'</h3>';
}
});
});
$('#area').append(item_html);
}
});
What you're asking for isn't possible with an object. Objects in Javascript are not ordered, only arrays. You have a few options:
Refactor your object to be an array
Refactor your object so that each key has a new key for order*
loop through each property of the object, placing it into an array (no guaranteed order!) and then looping through the array.
*Example:
[
{
"title": {
"value" : "A",
"order" : 4
},
"link": {
"value" : "google.com",
"order" : 5
...
}
]

Categories

Resources