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:
Related
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']);
});
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.
I have the following JSON object
{
"https://www.google.com": "200",
"https://www.facebook.com": "200",
"https://www.yahoo.com": "401",
"https://www.friendster.com": "404"
}
Is it possible to convert it to a JSON array with additional elements (url & status) in Javascript?
[
{
"url": "https://www.google.com",
"status": "200"
},
{
"url": "https://www.facebook.com",
"status": "200"
},
{
"url": "https://www.yahoo.com",
"status": "401"
},
{
"url": "https://www.friendster.com",
"status": "404"
}
]
Thank you for the tips.
Parse the string using JSON.parse, get all keys as an array and construct an array of objects with url and status properties
var json = '{\
"https://www.google.com": "200",\
"https://www.facebook.com": "200",\
"https://www.yahoo.com": "401",\
"https://www.friendster.com": "404"\
}';
var obj = JSON.parse(json);
var objWithUrlAndStatus = Object.keys(obj).map(function (key) {
return {
url: key,
status: obj[key]
}
});
console.log(objWithUrlAndStatus);
You can use jquery $.each
like this
var data = {
"https://www.google.com": "200",
"https://www.facebook.com": "200",
"https://www.yahoo.com": "401",
"https://www.friendster.com": "404"
};
var finalData=[];
$.each(data,function(index,val){
finalData.push({url:index,status:val});
});
console.log(finalData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have created a web service (asmx file) that returns a serialized ListItemCollection with the following code.
public string getStates(string Country)
{
ListItemCollection lic = DBInterface.GetStates(Country);
var serialized = JsonConvert.SerializeObject(lic);
return serialized;
}
I call the web service via javascript when a user selects a country from a dropdown list using the following code.
//ajax function that uses web services to get states
function GetStates(val)
{
$.ajax({
type: "POST",
url: "/WebServices/getServerData.asmx/getStates",
data: JSON.stringify({Country: val}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ddlState").empty();
var parsed = JSON.parse(data.d);
for (var i = 0; i < parsed.length; i++) {
$("#ddlState").append("<option value='" + parsed[i] + "'>" + parsed[i] + "</option>");
}
},
error: function (data) {
alert(data.status + " " + data.statusText);
}
});
}
The issue is that I want to also keep not only the ListItemCollection text, but also it's value. However the "JsonConvert.SerializeObject only returns the text items. Can someone help to return the value and text so that I can populate the dropdown via javascript?
Thanks!
One thing you can use the JavaScriptSerializer() in System.Web.Script.Serialization:
ListItemCollection lic = new ListItemCollection() {
new ListItem("Display Text", "val1"),
new ListItem("Display Text 2", "val2"),
};
var ser = new JavaScriptSerializer();
var serialized = ser.Serialize(lic);
Results in (I took the liberty to format) :
[
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text",
"Value": "val1"
},
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text 2",
"Value": "val2"
}
]
I keep getting an Uncaught SyntaxError: Unexpected token <, and I can not for the life of me , figure out why.
function democracyMap(resp) {
representative.fullName = resp.jurisdictions[5].elected_office[0].name_full;
representative.face = resp.jurisdictions[5].elected_office[0].url_photo;
representative.district = resp.jurisdictions[5].name;
senator1.fullName = resp.jurisdictions[6].elected_office[0].name_full;
senator1.face = resp.jurisdictions[6].elected_office[0].url_photo;
senator2.fullName = resp.jurisdictions[6].elected_office[1].name_full;
senator2.face = resp.jurisdictions[6].elected_office[1].url_photo;
representativeInfo();
senator1Info();
senator2Info();
apiSuccess();
}
function ajaxFail(req, status, err) {
console.log('something went wrong', status, err);
}
function getDemocracyMap(){
$.ajax({
type: "GET",
url: "http://api.democracymap.org/",
data:"location=",
crossDomain: true,
dataType: "jsonp",
success: function(resp) {
democracyMap(resp);
},
error: ajaxFail
});
}
Each representative, as well as sentator 1 and senator are set as global variables as such:
var representative = {
"fullName": "",
"firstName": "",
"lastName": "",
"district": "",
"face": "",
"party": "",
"termStart": "",
"termEnd": "",
"facebookID": "",
"twitter": "",
"youTube": ""
}