How to use the json? - javascript

I have called an api using href from the html form and it in response gives json as output.
consider this as the json the api gives
{
"entry":
{
"id": "1",
"name": "SA"
}
}
I want the values of the id and name.
How can i get the values specifically and store those values to a variable.
Also i got to do this in the html form with javascript.

I want the values of the city_id and city_name. How can i get the
values specifically and store those values to a variable
Use JSON.parse to convert it to JS object and get your values:
var obj = JSON.parse(yourJSON);
var city_id = obj['entry']['city_id'];
var city_name = obj['entry']['city_name'];
Docs:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse

var a;
eval('a={"entry":{"#collection_url":"http://api.storageroomapp.com/accounts/4fe004c598f46026cc000002/collections/4fe0063798f4602e2c000016","#created_at": "2012-06-21T09:12:40Z","#trash": false,"#type": "City","#updated_at": "2012-06-21T09:12:40Z","#url":"http://api.storageroomapp.com/accounts/4fe004c598f46026cc000002/collections/4fe0063798f460e2c000016/entries/4fe2e58898f4604757000006","#version": 1,"city_id": "City_001","city_name": "London"}}');
in other words
eval ('a={/*response object*/}')
now you have (a) as object that contains your data you can access them whether like object notation (a.entry) or as an array (a['entry'])
you can also use json parse but its not compatible with all browsers

Either the eval() function or the JSON parser will allow you to create an object from the JSON and then access the fields normally. The JSON parser is a little more secure, as explained in this tutorial:
http://www.w3schools.com/json/json_eval.asp

Related

Json Keys Are Undefined When Using Them From Script Tag

I've been trying to load certain Json with Ajax GET request and then parsing it.
However when trying to access the Json key from HTML script tag it was undefined.
In order to debug this issue, I logged all the keys of Json in console as well as the Json itself. Therefore i utilized this function:
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, "); // Explanation is below
console.log(invList[0]) // Just testing with first object
console.log(Object.keys(invList[0]));
});
}
getInv();
Purpose of data.split(",, "):
Since my backend script uses different programming language, I had to interpret it to the one suitable for Javascript.
There also were multiple Json objects, So i separated them with ",, " and then split them in Javascript in order to create a list of Json objects.
After calling the function, Following output was present:
Although the interesting part is that after pasting Json object in console like this:
This was the output:
So basically, in script tag, i was unable to access object's keys, although once i used it manually in console, all keys could be accessed.
What could be the purpose behind this? It seems quite strange that different outputs are given. Perhaps invList[0] is not Json object at all in the script tag? Thanks!
data.split() returns an array of strings, not objects. You need to use JSON.parse() to parse the JSON string to the corresponding objects.
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, ");
console.log(invList[0]) // Just testing with first object
var obj = JSON.parse(invList[0]);
console.log(Object.keys(obj));
});
}
You can use .map() to parse all of them, then you'll get an array of objects like you were expecting:
var invList = data.split(",, ").map(JSON.parse);

Access specific part of JSON JS

I am trying to access the t part of the "data": object below. I am doing this by doing console.log(message.data.f) however this returns undefined. I do not understand why I cannot access it in this way. See object below:
"data":"{\"e\":\"53845\",\"f\":\"SCORE\",\"pf\":[{\"p\":\"HOME\",\"v\":\"0\"},{\"p\":\"AWAY\",\"v\":\"0\"}],\"^t\":\"f\",\"i\":\"357575\",\"z\":1492771602631}",
Note I have marked the part of the object I wish to access with a ^
Your data property is a JSON string and probably all the object is a JSON string.
You need to parse the string as JSON
var obj = JSON.parse(myObj.data);
and then you can access:
console.log(obj.f);
If your first object, the one containing data, is not already a JSON too and its name is for example myFirstObject you need to do just this:
var jsonObj = JSON.parse(myFirstObject);
console.log(jsonObj.f);
Your message is nothing but string. Parse it first to a corresponding object to access its variables.
var parsed = JSON.parse(message);
console.log(message.data.t);

How to filter information from an output that consists of "X": "Y",

I'm working with NodeRed and using a Twitter node. I'm trying to figure out how to reply to users if they tweet 'X'.
The output consists of a load of information all comma separated and all consist of "x": "y",
As in
"User": "SanderSchaeffer", "Tweet": "This is my tweet", "date": "01-02-2015", etc.
How would I filter, preferably with Javascript or JSON, just the information that is contained by "user"? So the output would be 'SanderSchaeffer'?
Or bottom-line: How do I reply to a user with NodeRed? :)
Apologies for the inconvenient title, but I don't know the name of this way of information output
You can use the Node-RED Switch node to filter.
You can set it to act on the msg.payload value and use the contains option and then enter the text you want to match on into the box.
This should only allow Tweets which match through. You then probably want to use a function node to craft a suitable response.
EDIT:
To get just the sending user id then you would access it from within the function node as follows:
msg.tweet.user.screen_name
Try this one
var myOutput = '"User": "SanderSchaeffer", "Tweet": "This is my tweet", "date": "01-02-2015"';
var parse = JSON.parse('{'+myOutput +'}');
var userName = parse.User;
Javascript has a built in function to convert JSON data to a JavaScript Object. You can then access the JSON variables as an attribute of the object.
Just use the following code to parse the JSON to javascript:
var text = JSON code you retrieved;
var obj = JSON.parse(text);
You can then use the variable data by accessing them through the object:
document.write(obj.User);
document.write(obj.Tweet);
document.write(obj.date);
....
More information can be found at http://www.w3schools.com/js/js_json.asp
Which also explains how to access an array of JSON objects.

How can I get a specific value from a JSON URL, and pass it into a Javascript variable?

I want to use a JSON URL to get up-to-date exchange rates for use in a webpage. For this I want to be able to get a specific exchange rate (say, US Dollar) and pass the rate onto a variable so I can use it in a JS function.
Here is a sample of the JSON code:
"rates": {
"AED": 3.672796,
"AFN": 57.951451,
"ALL": 112.589601,
"AMD": 430.416,
"ANG": 1.787,
"AOA": 100.82775,
"ARS": 8.52454,
"AUD": 1.175504,
"AWG": 1.79,
"AZN": 0.784233,
"BAM": 1.571689,
"BBD": 2
Assign the JSON code to a variable, e.g.var json = "{your json string}" then parse it with var obj = JSON.parse( json );. Now you can access the elements from obj.
Use JSON.stringify to turn a JavaScript variable into a JSON string and JSON.parse to do the opposite. Then you can access properties directly (obj.SomeProperty) or dynamically (obj["SomeProperty"].

Json associative array accessing in jQuery

I am getting response in below format for every product and in a single call there can be many products. I am trying to access this data via jQuery but I'm not able to access it.
Productdata['someid'] = { "Product Json data"}
I am using below syntax in jQuery but not getting the data. Please suggest.
alert(Productdata['someid']);
Its not going as JSON format .
JSON is a key : value pair format ;
so your Productdata should be in below format:
Productdata = { 'someid' : "Product Json data"}
A Json like this
var data={"name":"somebody"};
To call
return data.name
Or
return data["name"]
The problem here is that JavaScript does not support associative arrays (scroll down to "Associative arrays, no way!"). It has some internal workarounds which make it appear as if it does, but really all it does is just adding the keys as properties.
So you would most likely be able to access it using Productdata.someid = ....
EDIT:
So assuming you have the following JSON string: {"id":"123"} (which is valid JSON), you can use it like this:
var jsonString = '{"id":"123"}';
var parsedJSON = $.parseJSON(jsonString);
var productID = "product_" + parsedJSON.id;
Does this help?
Some useful links: JSON format checker to make sure the JSON is valid.
Unfortunately I wasn't allowed to add more than 2 links, so the jQuery parseJSON function link is still in the comment below.

Categories

Resources