Can't access variables of JSON response from REST-API in Javascript - javascript

I have a problem getting access to the variables in a JSON-File. I get the file as a response from a REST-API. Here you can see the JSON-File:
{
"_embedded": {
"events": [
{
"name": "Josh.",
"type": "event",
"id": "Z698xZC2Z17CebP",
"test": false,
"url": "https://www.ticketmaster.de/event/josh-tickets/382625?language=en-us",
"locale": "en-us"
I want to access the value (Josh) of the "name" variable in Javascript in line number 5 and store it into a new variable to use it later.
This ist how I try to do it:
var = data._embedded.events[0].name
But I can't get access to the value attached to "name".
I have read the answers to similar questions here, but there was no solution for me.
I have only read, that it does not work because of the wrong JSON-structure. In other threads, they say there has to be a "{" instead of a "[" in line 3. But I don't know how to change it in javascript directly. I tried it with the JSON.stringify()-method but it didn't work out.
Can somebody help me, please? Is there any way to get access?
I hope you can understand my problem.
Thank you very much!

It seems that your json structure has some errors. The json structure similar to the following is legal. Of course, it is no problem to use a legal structure to exec data._embedded.events[0].name.
const data = {
"_embedded": {
"events": [
{
"name": "Josh.",
"type": "event",
"id": "Z698xZC2Z17CebP",
"test": false,
"url": "https://www.ticketmaster.de/event/josh-tickets/382625?language=en-us",
"locale": "en-us"
},
{
"name": "Josh.",
"type": "event",
"id": "Z698xZC2Z17CebP",
"test": false,
"url": "https://www.ticketmaster.de/event/josh-tickets/382625?language=en-us",
"locale": "en-us"
},
//...
]
}
}
console.log(data._embedded.events[0].name)

Related

Javascript parse JSON error, but works fine in validator

When I try to parse this JSON (Discord webhook):
{
"content": "this `supports` __a__ **subset** *of* ~~markdown~~ 😃 ```js\nfunction foo(bar) {\n console.log(bar);\n}\n\nfoo(1);```",
"embed": {
"title": "title ~~(did you know you can have markdown here too?)~~",
"description": "this supports [named links](https://discordapp.com) on top of the previously shown subset of markdown. ```\nyes, even code blocks```",
"url": "https://discordapp.com",
"color": 16324973,
"timestamp": "2018-12-18T09:22:12.841Z",
"footer": {
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png",
"text": "footer text"
},
"thumbnail": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"image": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"author": {
"name": "author name",
"url": "https://discordapp.com",
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"fields": [
{
"name": "🤔",
"value": "some of these properties have certain limits..."
},
{
"name": "😱",
"value": "try exceeding some of them!"
},
{
"name": "🙄",
"value": "an informative error should show up, and this view will remain as-is until all issues are fixed"
},
{
"name": "<:thonkang:219069250692841473>",
"value": "these last two",
"inline": true
},
{
"name": "<:thonkang:219069250692841473>",
"value": "are inline fields",
"inline": true
}
]
}
}
Using this code:
var parsed = JSON.parse(req.body)
I get this error:
SyntaxError: Unexpected token o in JSON at position 1
But if I use a website such as
https://jsonformatter.curiousconcept.com
To validate the JSON, it says the JSON is valid.
What is wrong here?
UPDATE
I'm using an express server to simulate discord server, so it sends web hooks to the express server instead, I get the JSON using req.body.
This happens because JSON is a global object (it's the same object where you read the method parse!), so when you invoke JSON.parse(JSON) javascript thinks you want to parse it.
The same thing doesn't happen when you pass the variable to the validator, because it will be assigned to a local variable:
let JSON = "{}";
validate(JSON);
function(x) {
JSON.parse(x); // here JSON is again your global object!
}
EDIT
According to your updated question, maybe it happens because you already use bodyParser.json() as middleware, and when you use it, req.body is already an object and you don't need to parse it again.
Trying to parsing an already parsed object will throw an error.
It would be something like without using JSONStream:
http.request(options, function(res) {
var buffers = []
res
.on('data', function(chunk) {
buffers.push(chunk)
})
.on('end', function() {
JSON.parse(Buffer.concat(buffers).toString())
})
})
For using it with JSONStream, it would be something like:
http.request(options, function(res) {
var stream = JSONStream.parse('*')
res.pipe(stream)
stream.on('data', console.log.bind(console, 'an item'))
})
(OR)
Here is the Some Steps for this issue..
You Can use lodash for resolving this.
import the lodash and call unescape().
const _ = require('lodash');
let htmlDecoder = function(encodedStr){
return _.unescape(encodedStr);
}
htmlDecoder(JSON);

How to extract specific info from json

I am trying to get the subdivisions.names.en from the json below but keep getting a "TypeError: location.subdivisions.names is undefined" error. I'm sure it something simple & prob just need more sleep ;)
I can get other the info I need - this works:
alert(location.city.names.en + ' ' + location.postal.code);
But this does not:
alert(location.subdivisions.names.en);
Here is my json:
{
"continent": {
"code": "OC",
"geoname_id": xxx,
"names": {
"fr": "Océanie",
"pt-BR": "Oceania",
"zh-CN": "大洋洲",
"es": "Oceanía",
"de": "Ozeanien",
"ja": "オセアニア",
"en": "Oceania",
"ru": "Океания"
}
},
"location": {
"longitude": xxxx,
"latitude": -xxxx,
"time_zone": "Australia/Melbourne"
},
"subdivisions":
[
{
"names": {
"ru": "Виктория",
"pt-BR": "Vitória",
"en": "Victoria"
},
"iso_code": "VIC",
"geoname_id": xxxx
}
],
}
"subdivisions": [ ... indicates, that this variable is an array of objects. You need to index the proper entry:
alert(location.subdivisions[0].names.en);
Please be aware that there must not be any entry
"subdivisions": [], ...
and a lot of them, so there must be some logic / check on the index.
location.subdivisions.length might help
"subdivisions" is defined as an array in your json file. Depending on what is intended, either change it to be just a hash (remove the square brackets) or modify the access to
alert(location.subdivisions[0].names.en);
You should have a look at what is JSON and how to use it properly because apparently you seem to lack the basic knowledge of how JSON is structured.
That being said, the reason why location.subdivisions.names.en is undefined is because in your JSON it does not exist.
subdivisions is also an array of objects.
In order to access what you are trying to you must use subdivisions[0].names.en.

How can I count fields in a JSON based on their content

I'm new to JS an this is likely a noob question, but I can't seem to find an answer which I figure may be due to my lack of correct terminology.
Basically I'm trying to count how many "active" fields in a JSON file are set to true vs false and return those values to a variable. I'm just getting lost trying to figure out how to go about this.
For example, my JSON is named data and looks like this:
{
"systems": [
{
"name": "SV001",
"IP": "10.1.1.101",
"active": "true"
},
{
"name": "SV002",
"IP": "10.1.1.102",
"active": "true"
},
{
"name": "SV003",
"IP": "10.1.1.103",
"active": "false"
}
]}
Any help would be greatly appreciated.
You could parse into the json object from string like
var json=JSON.parse(jsonString); And than by looping you can get the value.
var count=0;
for(var i=0i<json.systems.length;i++){
if(json.systems[i].active){
count++;
}
}
you can have count at the end of loop.

Get a specific element from JSON

I know this is a very simple and common question; I've already read some Q/A but I can't figure out how to solve my problem.
I have this short json from an AJAX call that execute a SPARQL query:
{
"head": {
"vars": [ "name" , "email" ]
} ,
"results": {
"bindings": [
{
"name": { "type": "literal" , "value": "Name Surname" } ,
"email": { "type": "literal" , "value": "name.surname#email.com" }
}
]
}
}
I'm searching name and email of a single user of the application, so
the result should be always made up of a single element.
What I want to retrieve is the "name" of the user.
I tried something like:
response["name"].value
//or
response[0]["name"]
//or
response.name
but always wrong.
How can I get the name value? Thanks to everyone who will help.
Try this
response.results.bindings[0].name.value
response.results.bindings[0].email.value
Update
Example
You can check out the fiddle created here
http://jsfiddle.net/uqxp4j73/
The code for this is as under
var x='{ "head": { "vars": [ "name" , "email" ] } , "results": { "bindings": [ { "name": { "type": "literal" , "value": "aadil keshwani" } , "email": { "type": "literal" , "value": "name.surname#email.com" } } ] }}';
obj = JSON && JSON.parse(x) || $.parseJSON(x);
console.log(obj);
console.log(obj["results"]["bindings"][0]["name"]["value"]);
alert(obj["results"]["bindings"][0]["name"]["value"]);
Hope this helps :)
In JSON, you always have to provide the full path to the property you like to reach. Assuming you have stored the parsed JSON in variable response, the following paths will get you corresponding value.
response.results.bindings[0].name.value for name
response.results.bindings[0].email.value for email
Recommend you to go through http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/ to get basic concepts of JSON.

Json returns every character as a separate object?

I have a json object that I'm loading from wordpress using the JSON API plugin. When I load the json object and try to log out the parts of it, it seems like it treats every single character as its own object so the loop returns me a couple thousand objects all with item in it which is a single character. This is my first time using json so idk if i'm missing a step here. this is the code I'm using so far.
function getProjInfo(theId){
$.ajax({// calling the ajax object of jquery
type: "GET",// we are going to be getting info from this data source
url: 'http://testing.charter21.com/api/get_post/?post_id='+ theId,//the datasource
dataType: "application/json",
success: function(data){
parseJson(data);
}, // what happens when it is successful at loading the XML
error: function(){
alert("error");
}
});
}//end of the function
function parseJson(inData){
postInfo = inData;
$.each(postInfo, function(index, value){
console.log(this);
});
}
the json looks like this:
{
"status": "ok",
"count": 10,
"count_total": 19,
"pages": 2,
"posts": [
{
"id": 175,
"type": "post",
"slug": "home-page-slider",
"url": "http:\/\/testing.charter21.com\/uncategorized\/home-page-slider\/",
"status": "publish",
"title": "Home Page slider",
"title_plain": "Home Page slider",
"content": "<p>The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.<\/p>\n",
"excerpt": "The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.",
"date": "2011-01-25 10:40:25",
"modified": "2011-01-25 10:40:25",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
"attachments": [],
"comment_count": 0,
"comment_status": "open"
}
so basically instead of giving me "status" as an key and "ok" as a value, i get "s" as an object with an index 0 that has a value of "s" for every single character in the json object. Any help on this matter would be appreciated.
You need to set dataType:json in your $.ajax() request so that jQuery converts the JSON-formatted string into a JavaScript object for you to process as such. You're currently using application/json which is a mime type, and not a valid value for this field in a jQuery request.
In your case you can even try data = eval(data) , this javascript statement should convert your string to json object.
Use the Jquery function:
data = $.parseJSON(data);
before using $.each.
The way I solved it in my AngularJS app is by sending the response from the server (I'm using Node Express) as a JavaScript object, rather than as a string. Nothing else worked for me.
var response = {};
response.error = "Error message";
res.send(response);

Categories

Resources