Im trying to convert JS Object to an Array but Array after conversion is undefined.
I initially have JSON but from what I have read it is automatically parsed into JS Object (when I try to parse it, I get SyntaxError: Unexpected token o in JSON at position 1). Also when I console.log(typeof cityList) I get Object.
Initial JSON goes like this:
[
{
"id": 707860,
"name": "Hurzuf",
"country": "UA",
"coord": {
"lon": 34.283333,
"lat": 44.549999
}
},
{
"id": 519188,
"name": "Novinki",
"country": "RU",
"coord": {
"lon": 37.666668,
"lat": 55.683334
}
}
]
I import JSON like this: import cityList from './city.list.json';
I use this code to convert:
const cityListArray = Object.values(cityList);
If I console.log(cityListArray) I get undefined.
I also tried: const cityListArray = Object.keys(cityList).map(i => cityList[i]) but result is the same.
Im not sure where the problem is. Any help would be appreciated!
You don't need to convert anything, since the JSON object is already an array.
You shouldn't check if something is an array with typeof since it returns "object" for arrays.
const a = [];
typeof a; // "object"
You should use the Array.isArray() method instead.
Related
I have below scripts on Google Apps Script which will take in an JSON event.
I want the data in element "events", but it always return "Undefined" to me.
I'm guessing maybe it's because events is a JSON array and I can't directly use it in JS?
Here is my code:
function doPost(e) {
var msg = JSON.parse(JSON.stringify(e.postData.contents));
console.log(msg);
//log succesfully
console.log(msg.events);
//"Undefined"
}
If I try to log the elements in the events instead of the array events itself:
console.log(msg.events[0].replyToken);
//"TypeError: Cannot read property '0' of undefined at doPost(app:26:25)"
The result of msg will is in below:
{
"destination": "U656de3c6b48c8e0d44edda4fd3f05e06",
"events": [
{
"type": "message",
"message": {
"type": "text",
"id": "*********",
"text": "Hi"
},
"timestamp": 1642616050062,
"source": {
"type": "group",
"groupId": "***********",
"userId": "*************"
},
"replyToken": "************",
"mode": "active"
}
]
}
I've seen several similar problems for array in JS.
I tried them but all of them didn't work, please help me.
I guess the result your getting from your API as e.postData.contents is a JSON string.
In this case something like this:
var msg = JSON.parse(JSON.stringify(e.postData.contents));
would first try to turn something into a JSON string (JSON.stringify) and then converting it into a JavaScript object by JSON.parse. In other words the JSON.stringify is useless.
Try this instead:
var msg = JSON.parse(e.postData.contents);
If the value from "e.postData.contents" is already a string, you don't have to do JSON.stringify.
If you do JSON.parse(JSON.stringify(any string) it results in adding backslash" to the values. For example
let str = '{name: "John"}';
let myJSON = JSON.stringify(str);
myJSON = "{name: "John"}"
So, please make sure "e.postData.contents" is not a string.
I am not sure if this is possible but here is the question:
I have the declared a constant grabbing partially an API's response body.
For simplicity, I will declare the partial API response as follows:
const partialResponse = {
"Name": "Marshall",
"Color": "Blue",
}
I am declaring a constant based on a array which includes the API's response body (stringified).
const data = {
"id": "123",
"jsonValues": partialResponse
}
However, in my script, the following returns null when I am expecting "Marshall" as an output:
console.log(data.jsonValues.Name)
I have the following sample json:
{
"camp": [
{
"name": "Name",
"data": [
{
"date": "04/08/2014",
"value": 1000
},
{
"date": "05/08/2014",
"value": 1110
}
]
}
]
}
Here, I'm able to do: model.get("camp")[0], but when I try: model.get("camp")[0].get("data"), I get the following error:
undefined is not a function
Here model is the standard backbone model which extends Backbone.Model
I'm confused what I'm doing wrong !!
You only need to call the model.get() function once. After that, you can treat the returned object just like any other javascript-object. For example, you could do this to get one of the values deep inside the object:
model.get("camp")[0].data[0].value
To achieve what you are trying to get, do this:
model.get("camp")[0].data
If you want to acces a property of your json array, you should simply do like this:
var test = json.camp.name
This is how you get your value:
obj.camp[0].data[0]
I have a JSON object that looks like this:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [ {... // contains lots objects with the data I'd like to access } ]
As noted above, I want to access the product array of objects. I can't seem to do this though. I've tried:
console.log(json['cj-api']['products'][0]['product']);
But I get typeError: Cannot read property 'products' of undefined.
What's the correct way to access the array of product (note, singular product, not products). This data is coming from an external source so I can't alter the hyphen in cj-api.
EDIT: Here's what the raw console log of json looks like:
{"cj-api":{"products":[{"$":{"total-matched":"231746","records-returned":"999","page-number":"1"},"product":[{ << lots of data in here>>
EDIT 2: To further clarify, I got this object by running JSON.stringify(result) after I put some XML into XML2js.
i have tried the following JSON structure:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [
{
"a": "a",
"b": "b",
"c": "c"
}
]
}
]
}
};
with the log statement as:
console.log(json['cj-api']['products'][0]['product']);
And result is as follows:
[Object { a="a", b="b", c="c"}]
Well your way of accessing json is absolutely correct. This is for debugging. Try
console.log(json['cj-api']);
console.log(json['cj-api']['products']);
console.log(json['cj-api']['products'][0]);
console.log(json['cj-api']['products'][0]['product']);
Which ever line returns undefined means your json is broken there.
If this doesn't work then you need to check for other similar keys. Maybe they value you are trying to find is actually undefined.
Maybe you are trying to loop. If you are then check for the condition if (JSONStructure[key]==undefined) console.log("Undefined at position ..."). That is the only way if you have valid JSON.
typeError: Cannot read property 'products' of undefined means that json exists, but json['cj-api'] is undefined. If you are sure that you are using the right variable name, I think this might be a scope issue, where you are using an other variable than you intend to. json might be the json string, instead of the array-like object. Try renaming your variable and see if you still get this problem. Otherwise the string is not automatically parsed for you and you'll have to parse it with JSON.parse( ... ).
Edit:
var json = '{ "me": "be an evil string" }';
console.log( json ); //'{ "me": "be an evil string" }'
console.log( json['me'] ); //undefined
console.log( JSON.parse( json )['me'] ); // 'be an evil string'
Since your question is missing the last
}
]
}
}
and others here changed your example and made it work, did you try to correct it?
If not then I suggest you or the dataprovider correct the structure of the reply.
I have tried below json structure
var json={
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": []
}
]
}
}
now json['cj-api']['products'][0]['product'] will work
Json is sitting on my localhost as: /data/:
{
"children": [
{
"name": "analytics",
"size": "1243"
},
{
"name": "math",
"size": "4343"
},
{
"name": "algebra",
"size": "1936"
},
{
"name": "calc",
"size": "3936"
},
{
"name": "geom",
"size": "2136"
},
{
"name": "Quant",
"size": "4136"
}
]
}
Here is how I am trying to access the json:
var interval = setInterval(function() {
$.getJSON("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) {
$.each(json.children,function(i,name){
alert(json.children);
});
});
}, 3000);
The data comes in just fine. That is, when I run console.log(json) I can see the above json name/value txt pairs in firebug. However, before each name value pair I see the word Object. So for example instead of my log showing { name="analytics", size="1243"},.. it actually shows: [Object { name="analytics", size="1243"},... And that too is what my alert shows: [object Object] instead of name="analytics", size="1243".
Why is this and is there a way to get my json name/value pairs in text so that I can store as a javascript String?
Many thanks in advance.
jQuery does automatically decode the response when using jQuery.getJSON or specifying the response as JSON. If you want the plain response, use jQuery.ajax instead.
The O in JSON stands for "object." It's a way of serializing a JavaScript object to a string (and back). You seem to be relying on the conversion on one hand (referencing children) but not want to have the conversion done on the other hand. If you really want children to be a collection of strings in the format you describe, you should store it that way. If you really do want the object notation (and conversion to objects in the client), then you can simply use the properties of the object.
var interval = setInterval(function() {
$.getJSON("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) {
$.each(json.children,function(i,item){
alert("name = " + item.name + ", size = " + item.size);
});
});
}, 3000);
Everything you've stated is normal behavior for both firebug and alert. You can't alert an object.
Here's example of how to loop the response within your $.get callback
http://jsfiddle.net/Y3N4S/
$.each(json.children, function(i, item){
$('body').append('<p>Name: '+item.name+' , Size: '+item.size+'</p>')
})
Well, working with Objects is the intend of "Javascript Object Notation".
Actually, your json is an Array of Objects.
{
"children": [ // <-- Array
{...},// <- Object
{...} // <- Object
]
}
You can access your key-value pairs this way: children[0].name
for (var i=0;i< children.length; ++){
console.log( children[i].name);
console.log( children[i].size);
}