I have looked at all similar questions to mine but cannot find any obvious errors in my code or my JSON string.
The script sends a request to a web service, which returns a JSON formatted string. Somehow, html related to debugging is getting tacked onto the end of the JSON string, so I remove it with the string.slice method, to return only the content between the opening and closing square brackets. When I output the slice, everything is there. When I check the resultant slice for proper JSON formatting in jsonlint, it passes. But when I try to parse the string and create an alert of the parsed data, I get an error: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse ) at XMLHttpRequest.request.onload
Here is the JSON string after slicing, taken directly from the jsonlint output:
[{
"user_id": "23",
"name": "Steven Marsden",
"email": "naturevet1#gmail.com",
"password": "$2y$10$FjDZAugd2Mj9tw.z8U1mWexLF0vkD7jnB5xusGyClDUXZwQC6u9iy",
"address": "2639 Valley Rdg Rd, Blairmore, AB T0K 0E0, Canada",
"lat": "49.617134",
"lng": "-114.388893",
"created_at": "2021-06-06 18:00:20",
"updated_at": "2021-06-06 18:00:20",
"services": [{
"u_s_id": "2",
"user_id": "23",
"mode": "seek",
"service": "pet sitting",
"details": "I have a dragon",
"img_file": null
}, {
"u_s_id": "3",
"user_id": "23",
"mode": "offer",
"service": "pet sitting",
"details": "I love dragons",
"img_file": null
}, {
"u_s_id": "7",
"user_id": "23",
"mode": "offer",
"service": "pet foster home",
"details": "Is it okay if my dragon eats your pet?",
"img_file": null
}],
"color": "red"
}]
Here is the javascript that requests the string and tries to parse it:
var url = 'http://localhost/helpinghands/public/index.php/services/getUsers';//Gets all users, complete with services offered and the appropriate marker color
var request = new XMLHttpRequest();
request.open('GET',url);
request.onload = function(){
if(request.status === 200){
var resp = request.responseText;
var slice = resp.slice(resp.indexOf('['),resp.indexOf(']')+1);//Cleaves any extraneous info from end of string to avoid JSON parse errors
var data = JSON.parse(slice);
//var userLat = Number(data[0].lat);
alert(data);
//var userLong = Number(data.lng);
//const loc = new point(userLat,userLong);//This is the location from the database for that user
//create marker object for loc by passing Marker constructor references to the loc and map objects, which are assigned to position and map variables, respectively
//const marker = new google.maps.Marker({map: map,position: loc, title: data.name});
}
};
Can anyone help me out?
Here is the output from the web service:
[{
"user_id": "23",
"name": "Steven Marsden",
"email": "naturevet1#gmail.com",
"password": "$2y$10$FjDZAugd2Mj9tw.z8U1mWexLF0vkD7jnB5xusGyClDUXZwQC6u9iy",
"address": "2639 Valley Rdg Rd, Blairmore, AB T0K 0E0, Canada",
"lat": "49.617134",
"lng": "-114.388893",
"created_at": "2021-06-06 18:00:20",
"updated_at": "2021-06-06 18:00:20",
"services": [{
"u_s_id": "2",
"user_id": "23",
"mode": "seek",
"service": "pet sitting",
"details": "I have a dragon",
"img_file": null
}, {
"u_s_id": "3",
"user_id": "23",
"mode": "offer",
"service": "pet sitting",
"details": "I love dragons",
"img_file": null
}, {
"u_s_id": "7",
"user_id": "23",
"mode": "offer",
"service": "pet foster home",
"details": "Is it okay if my dragon eats your pet?",
"img_file": null
}],
"color": "red"
}]
var slice = resp.slice(resp.indexOf('['),resp.indexOf(']')+1)
This function applied to your example JSON will cut off everything after the first ], which is the array nested under services, meaning that the first object in the json array will end up unclosed, as well as the json array that wraps the whole response.
You should fix the error in the server that returns HTML inside a JSON payload.
If that's not do-able, then you will need to detect the start of the HTML and cut there, though you are likely to keep experiencing more errors as a result of this faulty server endpoint
Related
I have a large json data that I have to parse and get object out of the following Json string. I added just top part of that large json data. I tried to parse it by
let obj = JSON.parse(this.state.data);
it doesn't work, it breaks with this msg "SyntaxError: Unexpected token L in JSON at position 0".
If I get the console.log by console.log(JSON.stringify(this.state.data, null, 2)); and try to validate output by online JSON validator, it says it is valid JSON data. Could you please tell me how can I parse it?
{
"content": [
{
"_id": 1,
"name": "Warehouse A",
"location": {
"lat": 47.13111,
"long": -61.54801
},
"cars": {
"location": "West wing",
"vehicles": [
{
"model": "GX",
"price": 27395.26,
"licensed": false,
"_id": 15,
"make": "Lexus",
"year_model": 2005,
"date_added": "2017-11-12T00:00:00.000+00:00"
},
{
"model": "Q",
"price": 6103.4,
"licensed": false,
"_id": 9,
"make": "Infiniti",
"year_model": 1995,
"date_added": "2017-11-13T00:00:00.000+00:00"
},
.........xxxxxx continue
Your variable this.state.data is not a JSON. It's a Javascript Object, just like JSON, So, Why not just use let obj = this.state.data;
i have below code i but data not show in console log please help me i am new in angular.. AND how to show data in HTML
this.$http.get(properties.client+'/123')
.then(response => {
$scope.clientdata= response.data;
console.log($scope.clientdata.address);
});
address array dose not show in console log,i don't know why RESPONSE BELOW
[{ "_id": "123",
"__v": 1,
"history": [],
"address": {
"street_address": "adsf",
"state": "adsf",
"zip_code": "adsf",
"phone_number": "asdf",
"country": "ads",
"city": "asdf",
"site_name": "adsf",
"_id": "123123",
"geolocation": {
"coordinates": [],
"type": "Point"
},
"location": {
"latitude": null,
"longitude": null
},
"id": "5835baaa71a30ca8319b6e36"
},
"current_status": "Assigned",
"time": 0
}]
Your clientdata is an array as per the post, try
console.log($scope.clientdata[0].address);
HTML
{{clientdata[0].address}}
From the structure of your JSON data, clientdata is an array of objects and as of current, there is only one object in the array. So, in order to access the address property of the object, you will have to access it in this way
$scope.clientdata[0].address
and in HTML
{{clientdata[0].address._id}}
and rest of the address object properties in similar fashion.
Is there a way to display the current number of members of my Facebook group on a SquareSpace code block (which only accepts HTML and JavaScript)?
Totally.
You can use Facebook Graph to accomplish what you want. Using an ordinary HTTPS request, I got this JSON-formatted results :
{
"id": "165227436975532",
"about": "Salon de Th\u00e9 style traditionnelle ..!!",
"can_post": false,
"category": "Restaurant/Cafe",
"category_list": [
{
"id": "203462172997785",
"name": "Tea Room"
}
],
"checkins": 66,
"cover": {
"cover_id": "476669145831358",
"offset_x": 0,
"offset_y": 54,
"source": "https://scontent.xx.fbcdn.net/hphotos-xpt1/v/t1.0-9/11536065_476669145831358_6075091507244297763_n.jpg?oh=7c6940ee3f2566884609fc59da224b67&oe=563A1B1D",
"id": "476669145831358"
},
"has_added_app": false,
"is_community_page": false,
"is_published": true,
"likes": 1246,
"link": "https://www.facebook.com/arabiccafe",
"location": {
"city": "Sousse",
"country": "Tunisia",
"latitude": 35.864546,
"longitude": 10.5988045,
"street": "Hammem Sousse",
"zip": "4011"
},
"name": "Arabica Cafe",
"parking": {
"lot": 0,
"street": 0,
"valet": 0
},
"phone": "21770198",
"talking_about_count": 6,
"username": "arabiccafe",
"were_here_count": 66
}
In order to get these info, you can use a normal XHR request (or jQuery.ajax if you use jQuery) and make a GET request to this URL :
https://graph.facebook.com/arabiccafe?access_token={your_token}
You can generate a token following these directives.
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
i have some data like :
{
"_id": ObjectId("528ae48e31bac2f78431d0ca"),
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
}
i want get description length and show it context
please help me!!
You don't provide much information, but here's an overview. I'm assuming you have a JSON string and not an object yet. I shall call him, "Jason Data" ...or rather jsonData.
Something like this for illustrative purposes (only without the new lines since you can't do multi-line strings in JavaScript in this fashion, but you get the idea):
// Jason Data, head full of doubt, road full of promises
var jsonData = '{
"_id": "528ae48e31bac2f78431d0ca",
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
}';
And then treat our outpatient, Jason Data:
// let's get his Mona Lisa
var data = JSON.parse(jsonData);
// since he holds numerous memories, let's first get the count (as you wish)
var numDescriptions = data.description.length;
// as if we were psychiatrists, we will now analyze each of his experiences
for ( var i = 0; i < numDescriptions; i++ ) {
// and write a poem about his life. (even though this goes against doctor-patient privilege, sue me)
console.log(data.description[i].id,data.description[i].des);
}
This is a JSON data you can stringfy and parse that data.
var data = JSON.stringify({
"_id": "ObjectId(528ae48e31bac2f78431d0ca)",
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
})
var parseData = JSON.parse(data)
parseData.description.length
1
parseData.description[0].id
"2"
parseData.description[0].des
"test"
Suggestion: You can get the value of ObjectId(528ae48e31bac2f78431d0ca) outside this format, and pass that as String to _id value
First of all you need to validate your json,
{
"_id": "528ae48e31bac2f78431d0ca",
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
}
This is a valid json. Now you can do the desired like this -
$.getJSON('assets/json/demo.json', function(data) {
$.each(data, function(key, value){
if(key === 'description'){
var description_length = value.length;
}
});
});
And to display its content you can again loop over "description" some what like this -
$.each(value, function(index, val){
alert(index+'-'+val);
});
Your question is not clear, anyway if you are looking to get value corresponding to key "description" then try this yourdata.description to get it's value
I have created these steps at http://jsfiddle.net/twmSk/1/
//storing your data into variable yourdata
var yourdata = {
"_id": ObjectId("528ae48e31bac2f78431d0ca"),
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
}
$('#test').html(JSON.stringify(yourdata.description))
I had this working the other day, I don't know what I did differently but I can't fetch the data to add into my collection. From tutorials and the docs this code should work right?
var Player = Backbone.Model.extend({});
var PlayersCollection = Backbone.Collection.extend({
url: "data/players.json",
model: Player
});
var playersCollection = new PlayersCollection();
playersCollection.fetch({
success: function(players) {
alert('success')
},
error: function() {
alert('fail')
}
});
I get the error with that, I am thinking I am missing something VERY easy. Maybe it is my JSON, here is a look at it.
[
{
"name": "JELLY Bryant",
"team": "Ballaz",
"team_id": "1",
"number": "24",
},
{
"name": "Lebron James",
"team": "Miami Heat",
"team_id": "2",
"number": "6"
},
{
"name": "Dwayne Wade",
"team": "Miami Heat",
"team_id": "2",
"number": "3"
},
{
"name": "Michael Beasley",
"team": "Miami Heat",
"team_id": "2",
"number": "30"
},
{
"name": "Carmelo Anthony",
"team": "New York Knicks",
"team_id": "3",
"number": "15"
},
{
"name": "Ron Artest",
"team": "New York Knicks",
"team_id": "3",
"number": "5"
},
{
"name": "Karl Malone",
"team": "Los Angeles Lakers",
"team_id": "1",
"number": "33"
},
{
"name": "Damion Lillard",
"team": "Portland Trailblazers",
"team_id": "4",
"number": "3"
},
{
"name": "Westly Matthews",
"team": "Portland Trailblazers",
"team_id": "4",
"number": "55"
},
{
"name": "Wilt Chamberlin",
"team": "Los Angeles Lakers",
"team_id": "1",
"number": "17"
}
]
Inside the network tab (chrome dev tools) it does make a successful get on the json.
Request URL:http://localhost/FRESH/data/players.json
Request Method:GET
Status Code:200 OK (from cache)
I have to be missing something here lol. I had some large code that was getting data from hard coded collection then when I switched to the url method it wasn't working so I stripped it to the bare basics, so it's obviously something ticky-tack I am missing.
WOOOOOOW I saw that I added an extra comma to the end of the first json model "JELLY Bryant" and that solved it, I didnt think that was such a big deal, I just noticed it now.
Your server sends an invalid JSON : you have a dangling comma in the first object. Check http://json.org/ for what constitutes a valid JSON format and some online tools like http://jsonlint.com/ can give you a quick check.
Try
[
{
"name": "JELLY Bryant",
"team": "Ballaz",
"team_id": "1",
"number": "24"
}
]