JSON data to JavaScript array - javascript

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.
}

Related

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

How to get JSON object's property? [duplicate]

This question already has answers here:
Safely turning a JSON string into an object
(28 answers)
Closed 7 years ago.
I want to parse a JSON string in JavaScript. The response is something like
var response = '{"result":true,"count":1}';
How can I get the values result and count from this?
The standard way to parse JSON in JavaScript is JSON.parse()
The JSON API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:
const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);
The only time you won't be able to use JSON.parse() is if you are programming for an ancient browser, such as IE 7 (2006), IE 6 (2001), Firefox 3 (2008), Safari 3.x (2009), etc. Alternatively, you may be in an esoteric JavaScript environment that doesn't include the standard APIs. In these cases, use json2.js, the reference implementation of JSON written by Douglas Crockford, the inventor of JSON. That library will provide an implementation of JSON.parse().
When processing extremely large JSON files, JSON.parse() may choke because of its synchronous nature and design. To resolve this, the JSON website recommends third-party libraries such as Oboe.js and clarinet, which provide streaming JSON parsing.
jQuery once had a $.parseJSON() function, but it was deprecated with jQuery 3.0. In any case, for a long time, it was nothing more than a wrapper around JSON.parse().
WARNING!
This answer stems from an ancient era of JavaScript programming during which there was no builtin way to parse JSON. The advice given here is no longer applicable and probably dangerous. From a modern perspective, parsing JSON by involving jQuery or calling eval() is nonsense. Unless you need to support IE 7 or Firefox 3.0, the correct way to parse JSON is JSON.parse().
First of all, you have to make sure that the JSON code is valid.
After that, I would recommend using a JavaScript library such as jQuery or Prototype if you can because these things are handled well in those libraries.
On the other hand, if you don't want to use a library and you can vouch for the validity of the JSON object, I would simply wrap the string in an anonymous function and use the eval function.
This is not recommended if you are getting the JSON object from another source that isn't absolutely trusted because the eval function allows for renegade code if you will.
Here is an example of using the eval function:
var strJSON = '{"result":true,"count":1}';
var objJSON = eval("(function(){return " + strJSON + ";})()");
alert(objJSON.result);
alert(objJSON.count);
If you control what browser is being used or you are not worried people with an older browser, you can always use the JSON.parse method.
This is really the ideal solution for the future.
If you are getting this from an outside site it might be helpful to use jQuery's getJSON. If it's a list you can iterate through it with $.each
$.getJSON(url, function (json) {
alert(json.result);
$.each(json.list, function (i, fb) {
alert(fb.result);
});
});
If you want to use JSON 3 for older browsers, you can load it conditionally with:
<script>
window.JSON ||
document.write('<script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.2.4/json3.min.js"><\/scr'+'ipt>');
</script>
Now the standard window.JSON object is available to you no matter what browser a client is running.
The following example will make it clear:
let contactJSON = '{"name":"John Doe","age":"11"}';
let contact = JSON.parse(contactJSON);
console.log(contact.name + ", " + contact.age);
// Output: John Doe, 11
If you pass a string variable (a well-formed JSON string) to JSON.parse from MVC #Viewbag that has doublequote, '"', as quotes, you need to process it before JSON.parse (jsonstring)
var jsonstring = '#ViewBag.jsonstring';
jsonstring = jsonstring.replace(/"/g, '"');
You can either use the eval function as in some other answers. (Don't forget the extra braces.) You will know why when you dig deeper), or simply use the jQuery function parseJSON:
var response = '{"result":true , "count":1}';
var parsedJSON = $.parseJSON(response);
OR
You can use this below code.
var response = '{"result":true , "count":1}';
var jsonObject = JSON.parse(response);
And you can access the fields using jsonObject.result and jsonObject.count.
Update:
If your output is undefined then you need to follow THIS answer. Maybe your json string has an array format. You need to access the json object properties like this
var response = '[{"result":true , "count":1}]'; // <~ Array with [] tag
var jsonObject = JSON.parse(response);
console.log(jsonObject[0].result); //Output true
console.log(jsonObject[0].count); //Output 1
The easiest way using parse() method:
var response = '{"a":true,"b":1}';
var JsonObject= JSON.parse(response);
this is an example of how to get values:
var myResponseResult = JsonObject.a;
var myResponseCount = JsonObject.b;
JSON.parse() converts any JSON String passed into the function, to a JSON object.
For better understanding, press F12 to open the Inspect Element of your browser, and go to the console to write the following commands:
var response = '{"result":true,"count":1}'; // Sample JSON object (string form)
JSON.parse(response); // Converts passed string to a JSON object.
Now run the command:
console.log(JSON.parse(response));
You'll get output as Object {result: true, count: 1}.
In order to use that object, you can assign it to the variable, let's say obj:
var obj = JSON.parse(response);
Now by using obj and the dot(.) operator you can access properties of the JSON Object.
Try to run the command
console.log(obj.result);
Without using a library you can use eval - the only time you should use. It's safer to use a library though.
eg...
var response = '{"result":true , "count":1}';
var parsedJSON = eval('('+response+')');
var result=parsedJSON.result;
var count=parsedJSON.count;
alert('result:'+result+' count:'+count);
If you like
var response = '{"result":true,"count":1}';
var JsonObject= JSON.parse(response);
you can access the JSON elements by JsonObject with (.) dot:
JsonObject.result;
JsonObject.count;
I thought JSON.parse(myObject) would work. But depending on the browsers, it might be worth using eval('('+myObject+')'). The only issue I can recommend watching out for is the multi-level list in JSON.
An easy way to do it:
var data = '{"result":true,"count":1}';
var json = eval("[" +data+ "]")[0]; // ;)
If you use Dojo Toolkit:
require(["dojo/json"], function(JSON){
JSON.parse('{"hello":"world"}', true);
});
As mentioned by numerous others, most browsers support JSON.parse and JSON.stringify.
Now, I'd also like to add that if you are using AngularJS (which I highly recommend), then it also provides the functionality that you require:
var myJson = '{"result": true, "count": 1}';
var obj = angular.fromJson(myJson);//equivalent to JSON.parse(myJson)
var backToJson = angular.toJson(obj);//equivalent to JSON.stringify(obj)
I just wanted to add the stuff about AngularJS to provide another option. NOTE that AngularJS doesn't officially support Internet Explorer 8 (and older versions, for that matter), though through experience most of the stuff seems to work pretty well.
If you use jQuery, it is simple:
var response = '{"result":true,"count":1}';
var obj = $.parseJSON(response);
alert(obj.result); //true
alert(obj.count); //1

JavaScript - Converting JSON object to String

I have a JSON object in following format which I need to convert to pure String...as 0000-0000-0000-0000-000 so I was wondering how I can do this in Javascript?
{ KEY: "0000-0000-0000-0000-000" }
try this (where data is the data returned from the API call)
var tokenString = data.KEY;
alert(tokenString);
try
console.log(obj)
to view it in the browser debugger console
or
JSON.stringify(obj);
I would recommend using
JSON.stringify()
Extra info on this method can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Your object is not JSON when it's in JavaScript, it's JavaScript code. The string version you're asking for is JSON (JavaScript Object Notation). This is why you can do things in JavaScript that you cannot do in JSON, like representing functions and binary data.
The function you're looking for to turn your JavaScript object into JSON is JSON.stringify() which you would use like this:
var obj = { }; //put your object here
console.log(JSON.stringify(obj)); //output the JSON version of your object
Also, the object in your question is not valid JSON or JS. In either scenario you'd need to put quotes around the 0000-0000-0000-0000-0000 and give it a value. The following is valid JSON:
{ "0000-0000-0000-0000-0000": null }
Store your response in one variable and then do
response.KEY

Query regarding Difference between JavaScript Object And JSOn Object

Here is my question:
in java script:
we hav an object:
var someObject={"name":"somename"};
Now we want to get the name ,we ll do
alert(someObject.name); //it will print somename Right?
Same object i get from a source which sends a JSON object as
someJSONObject={"name":"someName"};
Now in my javascript code ,without parsing this someJSONObject ,i can get name as
alert(someJSONObject.name);
If it is so ,why we need to convert JSON Object to a javaScript Object by parsing it ,when we can use it as an object without parsing or using eval()?
Thanks !
Because it's not a JSON Object. The syntax {"name":"someName"}, with quoted keys, does not make it JSON, the same syntax is supported by Javascript object literals.
JSON can be embedded in Javascript strings. Like:
var json = '{"key": "value"}';
Then you can parse it into Javascript data types:
var obj = JSON.parse( json );
Note that eval may cause syntax errors because the syntaxes of JSON and Javascript are not ultimately compatible. The above would have caused a syntax error if evaled.
JSON is a string, so it's something like var jsonObject = '{"name":"someName"}'; an object is an object.

How to get data from JSON response?

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.

Categories