How to get data from JSON response? - javascript

I am using plain JavaScript on my project. How can I get the value of the following example with the category? I need to detect whether it comes back true or false.
{
"category": "true"
}
I can get the entire object, but I just want to pull out the value of category.
from comment...
The JSON data is returned from the server based on a form submission. It keeps saying myObject is undefined. How can do I pass this so my JavaScript can read the response?
from comment...
I can get myObject using this: if (form.XHR.status === 200) {var data = form.XHR.response;}, but if I try to do data.myObject it says it's undefined.

You need to parse the JSON before you can access it as an object...
if (form.XHR.status === 200) {
var data = form.XHR.response;
var parsed = JSON.parse(data);
alert(parsed.category);
}
Why is this needed? It's because JSON is not JavaScript. The two terms are not synonymous.
JSON is a textual data interchange format. It needs to be parsed into the data structures of whatever language it's been given to. In your case, the language is JavaScript, so you need to parse it into JavaScript data.
When it is received form the xhr response, it is received in the form in which all textual data is handled in JavaScript. That is as a string. As a string, you can't directly access the values represented.
JavaScript has a built in parser called JSON.parse. This was used in the example above to do the necessary conversion.
Some older browsers don't support JSON.parse. If you're supporting those browsers, you can find a JavaScript parser at http://json.org .

First of all you need a variable to refer it:
var obj = {
"category": "true"
};
Then can you say e.g:
alert(obj.category);

var myObject = { "category": "true"};
alert (myObject.category);
But you likely want:
var myObject = { "category": true};
...if you're going to be testing for true/false:
if (myObject.category) {
// category is true, so do your stuff here.
}

You can access json object data using '.' or [key] like this :
var obj = {
"category": "true"
};
console.log(obj.category);
// Or
console.log(obj["category"]);
Here is the DEMO

For anyone who arrives here banging their head against the wall, make sure to see if you need to access a parent object which wraps all the delivered data:
console.log(response['id'])
may not work, because a parent entity must be accessed first:
console.log(response.session['id'])
If you console log your response and it is wrapped in {} you probably need to do this.

Related

CognitiveServices POST response: data.hasOwnProperty failing for all but root of nested JSON object using raw JS

I am posting a request to Azure Cognitive Services (sentiment API) which returns a nested JSON object as follows (this is a JSON.stringify object output):
{ "error": "{\"documents\":[{\"id\":\"1\",\"sentiment\":\"neutral\",\"documentScores\":{\"positive\":0.15,\"neutral\":0.8,\"negative\":0.05},\"sentences\":[{\"sentiment\":\"neutral\",\"sentenceScores\":{\"positive\":0.15,\"neutral\":0.8,\"negative\":0.05},\"offset\":0,\"length\":4}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}" }
I have spent 3 days trying and failing to access the nested key:values using javascript, so I can write individual keys/values to HTML elements using raw JS.
I've validated the JSON is correct using jsonlint.com
I've tried removing '/' characters by both re-parsing, and .replace, but the "cleaned" JSON still does not provide access to documents[]
I've used the following function, found on SO, to validate the stringify string against the object:
//Get nested object structure with key names
function traverse_it(data){
for(var prop in data){
if(typeof data[prop]=='object'){
// object
traverse_it(data[prop[i]]);
}else{
// something else
alert('The value of '+prop+' is '+data[prop]+'.');
}
}
}
traverse_it(data);
I've used data.hasOwnProperty to test for property existence - the only property that returns TRUE is "error":
//Check for individual properties
if(data.hasOwnProperty("error")){
console.log(data.error);
alert('yippidydippity')
}else{
alert('nope')
}
Attempts to access error.documents, error.documents[0].id, or locate the documents array all fail. I've searched through similar problems on SO but have not found anything that works.
How can I access the individual keys and values of this object using JS? Many thanks in advance!!!
try this
let obj = { "error": "{\"documents\":[{\"id\":\"1\",\"sentiment\":\"neutral\",\"documentScores\":{\"positive\":0.15,\"neutral\":0.8,\"negative\":0.05},\"sentences\":[{\"sentiment\":\"neutral\",\"sentenceScores\":{\"positive\":0.15,\"neutral\":0.8,\"negative\":0.05},\"offset\":0,\"length\":4}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}" }
let obj2 = JSON.parse(obj.error)
//now you can access id from object
console.log(obj2.documents[0].id)

JSON object recieved from api property returns undefined

For the project that I am working on, I am using the Shopify API which allows you to retrieve products and other information from your store to be retrieved in the format of a JSON object. I was able to successfully get the JSON object from the API, however when I try to access a property of the JSON object, it returns undefined. I have looked at a couple of articles that I will refrence below, but the problem for those users were things such as needing to use:
JSON.parse()
for a JSON object enclosed by strings which is not my probelem, I have tried a few other work arounds as well but with no luck, I originally thought that the problem was that my code needed to use an "Async/Await" function in order to wait for a response from the API, but I then realized that wouldn't make sense considering I can recieve the whole JSON object itself with no problems.
When I use:
request.get(url, {headers})
.then( result => {
console.log(result); // Only accessing object itself
});
I recieve the JSON object response correctly with no error like this:
{"products":[{"title":"Test Product 1","body_html":"This is a product that is being tested for retrieval!",
"product_type":"","created_at":"2018-08-21T17:49:07-07:00","handle":"test-product-1","updated_at":"2018-08-21T17:49:07-07:00","published_at":"2018-08-21T17:48:19-07:00","template_suffix":null,"tags":"",
"published_scope":"web","variants":[{"title":"Default Title","price":"5.00","sku":"","position":1,"inventory_policy":"deny",
"compare_at_price":null,"fulfillment_service":"manual","inventory_management":null,"option1":"Default Title","option2":null,"option3":null,
"created_at":"2018-08-21T17:49:07-07:00","updated_at":"2018-08-21T17:49:07-07:00","taxable":true,"barcode":"",
"grams":99790,"image_id":null,"inventory_quantity":1,"weight":220.0,"weight_unit":"lb","old_inventory_quantity":1,
"requires_shipping":true,}],"options":[{"name":"Title","position":1,"values":["Default Title"]}],"images":[],"image":null}]}
However when I use this, the JSON object property returns undefined:
request.get(url, {headers})
.then( result => {
console.log(result.products[0]); // Accessing the first item in JSON "products" array
});
Articles I have already checked out:
cannot access json object property returns undefined
JSON object returns undefined value
JSON objects returns undefined
Would anyone be able to explain my error or why this is happening? I am more than happy to edit my question to include any code/information that might be helpful.
Thanks in advance,
Michael
try this:
console.log("data:", JSON.stringify(result.products[0], null, 2));
console.log to print the result to your console. Use Chrome and developer tools and you will see a console option - excellent for debugging.
JSON.stringify turns the JSON data into something you can see and read. You can convert the data and then split as you need this way too.
OK, a second answer. I can't check this, as I don't have your JSON data, however, I would try something that would likely resemble this...
data.Items[0].field
if the data is not correctly formatted then take the stringify approach and split it out. Otherwise, consider this:
products":[{"title":"Test Product 1"
variable = products[0].title;
I would tend to use a function to pull all the data out in one shot.
function Getv(data){ global.myApp.v = JSON.stringify(data, null, 2); }
then I might run this...
Getv(data.Items[0]); let splitData = global.myApp.v.split('\"'); let vCount= splitData.length;
if the object returns like this it wouldn't work because it's missing a colon after "products" identifier. like Luca said it's not a valid JSON response
Try this:
var resultJson = JSON.parse(result);
console.log(resultJson.products[0].varname);

JSON data to JavaScript array

I'm having problems handling JSON-data as an array in JavaScript.
my JSON array looks like this :
MyArray([['one','two','three'],['four','five','six']]);
In JS I am trying to receive it using this method :
$.getJSON('http://test.com/array.json', function(data) {
alert(data);
}
but i get no data. If i'm using
$get('http://test.com/array.json', function(data)
instead of $getJSON then i receive my data as a string.
Any help would be greatly appreciated.
Your data is not JSON, but JSONP, where MyArray is the JSONP callback function.
In theory the web service you're talking to should support a callback= parameter which would be what sets the MyArray name.
If you just add &callback=? then jQuery should automatically generate a randomly named callback function which will then call your success function with the required data.
This is no JSON :
MyArray([['one','two','three'],['four','five','six']]);
A JSON string isn't simply some javascript you want to evaluate but must start by [ or {.
Look at the norm : http://www.json.org/
As you seem to have a constructor at first, this is probably not even JSONP.
I'd recommend you to make a standard JSON array :
"[['one','two','three'],['four','five','six']]"
And then use a constructor client side if you need a MyArray instance.
Your JSON isn't valid. The format it's in can still be used. Use the get method and then try the following:
$.get('http://test.com/array.json', function(data) {
data = data.replace("MyArray(", '"');
data = data.replace(");", '"');
var myData = JSON.parse(data); // Converted JSON to object.
}

Accessing Json in Javascript

'[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]'
When I try to access the above like this:
for (var i = 0; i < data.length; i++) {
alert(data[i]);
}
It spells out each thing, such as [, {, ", S, and etc.
I also tried doing data[i].SponsorName but obviously got undefined. How should I be accessing this?
You need to parse the JSON string, preferably with JSON.parse. The JSON API is built into more modern browsers and can be provided to older browsers by including Crockford's JSON script. Crockford's script will detect if the browser already provides the API and adds it if not.
With that in place, if your JSON is in a string variable named response, you can:
var parsedResponse = JSON.parse( response );
//run your iterating code on parsedResponse
You would first need to eval() or more ideally JSON.parse() the JSON string in to a Javascript object. This assumes you trust the source of the JSON.
var jsonobj = JSON.parse(data);
// Now view the object's structure
console.dir(jsonobj);
Here's what it looks like after being evaluated and printed out:
var array = JSON.parse('[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]')
array[0].AccountingManager; // "me"
Or everyone's favorite library, since IE7 and below don't have native support:
$.parseJSON('[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]')
You parsed the Json string first, right?
var data = '[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]';
data = JSON.parse(data);
alert(data.SponsorName);
JSON.parse, when available, is the preferred method over "eval" because of security and performance issues.
You've got a JSON array followed by an object:
var data = [{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}];
alert(data[0].SponsorID);

How do I add JSON object as new level to another JSON object?

I have a code that gets in the end collection of two JSON objects, something like this.
var jsonL1 = {"holder1": {}}
var jsonL2 = {"section":"0 6","date":"11/12/13"}
I would like to insert jsonL2 inside jsonL1.holder1 and merge it to one JSON object.
Desired output
{
"holder1": {
"section": "0 6",
"date": "11/12/13"
}
}
How can I do that?
It is as easy as:
L1.holder1 = L2
I removed the "json" from the variable names, as #patrick already said, you are dealing not with "JSON objects" but with object literals.
See also: There is no such thing as a JSON object
You also might want to learn more about objects in JavaScript.
If you want the first object to reference the second, do this:
jsonL1.holder1 = jsonL2;
If you wanted a copy of the second in the first, that's different.
So it depends on what you mean by merge it into one object. Using the code above, changes to jsonL2 will be visible in jsonL1.holder, because they're really just both referencing the same object.
A little off topic, but to give a more visual description of the difference between JSON data and javascript object:
// this is a javascript object
var obj = {"section":"0 6","date":"11/12/13"};
// this is valid JSON data
var jsn = '{"section":"0 6","date":"11/12/13"}';

Categories