Json to Javascript object or Array [duplicate] - javascript

This question already has answers here:
Convert javascript object or array to json for ajax data
(2 answers)
Closed 9 years ago.
I am developing a site on Django framework which returns a json response to be used jquery datatable. Datatable requires input to be either javascript object or array of arrys so i need to convert this on either server side or client side to javascript object or array.
Here is the related documentation for the datatable.
DataTables AJAX source example
DataTables AJAX source example - array of objects as a data source
[
{
"pk": 7,
"model": "softwareapp.software",
"fields": {
"city": "miami",
"submitted_by": [],
"description": "test",
"title": "test",
"zipcode": "test",
"rating_votes": 0,
"state": "fl",
"address": "test",
"rating_score": 0,
"business_size": [
5
],
"slug": "test",
"developer": "test"
}
},
{
"pk": 8,
"model": "softwareapp.software",
"fields": {
"city": "",
"submitted_by": [],
"description": "",
"title": "test2",
"zipcode": "",
"rating_votes": 0,
"state": "",
"address": "",
"rating_score": 0,
"business_size": [
5
],
"slug": "test2",
"developer": ""
}
},
{
"pk": 10,
"model": "softwareapp.software",
"fields": {
"city": "",
"submitted_by": [],
"description": "",
"title": "test3",
"zipcode": "",
"rating_votes": 0,
"state": "",
"address": "",
"rating_score": 0,
"business_size": [
6
],
"slug": "test3",
"developer": ""
}
}
]

Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.

On the client you could use:
JSON.parse(json)
"json" being the JSON string .
Or if you're also using jQuery to do the AJAX request it will do the deserialization for you in the "success" handler.
$.ajax({
type: "GET",
url: "your url",
dataType: "json",
contentType: "application/json",
success: function (e) {
// the value of "e" should be a javascript object or array depending on the response
}
});

Related

How to make JavaScript object from the given json string

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;

Json parse javascript : String displayed as NAN [duplicate]

This question already has answers here:
Unable to access JSON property with "-" dash [duplicate]
(5 answers)
Closed 5 years ago.
So i am trying parse a json file. I am using alert to get the value of a particular field but whenever i pass this particular string it is displayed as nan
myjsondata=JSON.parse(json);
alert(myjsondata.result.parameters.College-name);
Json file
`{
"id": "1",
"timestamp": "2017-05-11T04:03:26.008Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "hi",
"action": "input.welcome",
"actionIncomplete": false,
"parameters": {
"College-name": "Apex Technical School"},
"contexts": [],
"metadata": {
"intentId": "b11a9493-7c2f-47c0-9928-5653a10c86e9",
"webhookUsed": "false",
"webhookForSlotFillingUsed": "false",
"intentName": "Default Welcome Intent"
},
"fulfillment": {
"speech": "Hi welcome from webfocus Api Ai",
"messages": [
{
"type": 0,
"speech": "Hi welcome from webfocus Api Ai"
},
{
"type": 0,
"speech": ""
}
]
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success"
},
"sessionId": "04737548-a3ff-485d-af1a-304edfee9486"
}`
alert with action and other fields are working fine . But for college it is displayed as NAN
You are getting a null value because parameters does not have a key called College-name:
"parameters": {},
Also, you might want to change your selection be using:
alert(myjsondata.result.parameters['College-name']);

angularjs response data does not show in console

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.

Display current number of Facebook group members using JavaScript

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.

How to get some data from json array length and context [duplicate]

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))

Categories

Resources