My code returns a JSON array, I think. The returned JSON array is stored in a javascript variable: result. If I
console.log(result);
in FF, I get the output
[{"id":"G24","value":"Zas, S"},{"id":"G75","value":"Wara, TS"},{"id":"G48","value":"Jala, S"}]
Validated on jsonLint to be correct json.
In my code, if I count the number of elements in the array like so:
var key, count = 0;
for(key in result)
{
count++;
}
console.log("result count is:" + count);
The output is 94 which is the length/count of characters in the array - [the sample output shown above is modified]
However, in the JSON tab in FF, it shows the result as being an array of objects:
0 Object { id="G24", value="Zas, S"}
1 Object { id="G75", value="Wara, TS"}
2 Object { id="G48", value="Jala, S"}
I have used alternative code pieces from 'stackoverflow' sources
for ( property in result )
{
if(result.hasOwnProperty(property))
{
count++;
}
}
And this has had the same outcome. How can I have iterate rightly over this array or array of objects or string or whatever else it is? And get the count please?. Thanks.
It sounds like you have an HTTP response returning a JSON document.
In the JSON tab, this is shown as JSON.
If your code, you are just taking the text of the response and operating on that.
You need to parse the JSON to create JavaScript objects.
Pass the string through JSON.parse and use json2.js to polyfill for older browsers.
You have to parse the JSON to create a JavaScript Array.
result = JSON.parse(result); // Now it's an array
console.log(result.length) // prints now what you want
Related
I just realized that when I make a POST request like this:
async createProduct(){
let formData = new FormData();
formData.append("name", "test")
formData.append("price", 150)
formData.append("brands", [1, 2])
let response = await axios.post("/createProduct", formData)
}
And then console.log() the typeof each property on the back-end, I always get a string:
console.log(typeof req.body.brands) --> String 1, 2
console.log(typeof req.body.price) --> String 150
Why is this happening and how can I turn them to their original data types? I guess I can turn the req.body.price to integer with parseInt(), but how to turn req.body.brands back to an array?
I'm assuming you're using something like multer as a body parser to handle form-data.
You are adding the array wrong. The formData.append() function only accepts a string as argument. This causes [1,2] to be converted to a string automatically which conveniently is equal to [1,2].join(', ').
However, form-data does indeed support multiple values which multer will parse into arrays. But note that it support multiple values. Not arrays. So the correct syntax to add an array of values is:
formData.append("brands", 1);
formData.append("brands", 2);
Or more generally:
[1,2].forEach(x => formData.append("brands", x));
Doing this your backend should correctly parse the values into an array:
console.log(typeof req.body.brands) --> Array [1,2]
Your question is very confusing. How do you console.log() on the back-end?
If you meant, front-end and you are using PHP or whatever, if you receive an object response, you still have to convert it to your desired data type.
For JSON
var a = JSON.parse(response)
Then if you're expecting an array,
you should make the response an array type in the server. That way, Javascript will automatically detect it as an array.
console.log(response.length)
If you want convert your data to array in the server:
$data = array(1,2,3);
Then ensure you use a proper encoding type to flush response back to the HTML page.
echo json_encode($data);
If you already have your data and want to convert it to an array, do this:
var arr = [];
var data = response.split(',');
//Loop through data
for(var x=0;x < data.length;x++) {
arr.push(data[x]);
}
console.log(typeof arr) //Array (Object)```
Ordinarily, The ```arr = arr.split(',');```
is already an array and can be worked on
is there anyway i can get this malformed json format which is odd i have no control over this json manually so i need to get this data and manipulate it with rxjs observable from http get
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
}
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
}
I tried with your JSON in the console and this seems to work. In the map function I've used you can probably implement more generic replacement methods to alter the strings, but it works for this example.
function fixBadJSON(response){
let badJSON = JSON.stringify(response); // added this edit in case you don't know how to get the response to a string
let arr = badJSON.split('}\n'); // Looks like the JSON elements are split by linefeeds preceded by closing bracket, make into arr length of 3
let fixedArr = arr.map((item)=>{ // map the array to another, replace the comma at the end of the avatarImage key. elements in array should be proper JSON
if(item[item.length] != '}') item += '}'; //put the brackets back at thend of the string if they got taken out in the split, probably a better way to handle this logic with regex etc
return item.replace('jpg",','jpg"')
});
let parsedJSON = JSON.parse(JSON.stringify(fixedArr));
return parsedJSON
}
Take the JSON data you've posted up there and copy it to a variable as a string and test the function, it will return a properly formatted array of JSON data.
Call that when you get a response from your service to transform the data. As far as the observable chains and any async issues you might be seeing those are separate things. This function is just designed to convert your malformed JSON.
I have read other issues regarding accessing a json array in javascript, but nothing helped in my case.
I am receiving the below json in jquery ajax call.
{"jList":"[{\"added_by\":\"Ani\",\"description\":\"example description.\",\"start_date
\":\"2014-10-10\",\"mark\":255,\"id\":975},{\"added_by\":\"Ani\",\"description
\":\"example description..\",\"start_date\":\"2014-10-10\",\"mark\":255,\"id\":980
}]"}
receiving method-
$.getJSON("url",
{var : Val},
function(data){
here...
All I want is to count the JSON objects in this array. In the above case I want an length output as 2 but I'm not getting it.
I have tried below things-
data.jList.length -- < giving 200 like something as output
Object.keys(data).length -- < giving 200 like something as output
Object.keys(data['jList']).length -- < giving 1 as output
How do I get 2 as length output of the above array?
The jList property of the object is just a string, so you need to convert it to a Javascript object using JSON.parse().
// Dummy of your "data" variable
var data = {"jList":"[{\"added_by\":\"Ani\",\"description\":\"example description.\",\"start_date \":\"2014-10-10\",\"mark\":255,\"id\":975},{\"added_by\":\"Ani\",\"description \":\"example description..\",\"start_date\":\"2014-10-10\",\"mark\":255,\"id\":980 }]"};
var myList = JSON.parse(data.jList);
alert(myList.length); // Alerts "2"
"jList":"[{\"added_by\":\"... is not an array, it's a string (and that's why it's length is 456 or 200 if you change the question).
Remove the surrounding double-quotation marks for it to be an array. Then you'll have Array.prototype.length.
I have json returned from Database.I want to pick only one object Value and show it in the textbox. Here is my json.
[{
"ErrorMessage":"",
"ID":294,
"ExpenseID":0,
"EffectiveDate":"/Date(1262284200000)/",
"FormattedEffectiveDate":"01-01-2010",
"Perunit":null,
"VATRate":17.5,
"ChangedByID":1,
"ChangedByName":"superuser, superuser",
"Expense":null,
"ErrorSummary":null,
"ErrorList":[]
}]
I have Tried
var Jsoninvoice = JSON.stringify(data)
alert(Jsoninvoice.VATRate) and also alert(data.VATRate)
Thank you In advance.
You have an array containing 1 object. stringify turns this object into a string - you need it parsed so you can use it.
(I'm not sure if the object is parsed already, so to cover all bases, we'll parse it)
var Jsoninvoice = JSON.parse(data);
alert(Jsoninvoice[0].VATRate);
You have to specify the arrays index before you can access the properties.
It is already json object and stringify is not needed as #tymJV said you need to parse it if it is returned as string, just you need to access array item, as it is an array:
alert(data[0].VATRate)
SEE FIDDLE
You could use $.parseJSON(YOURJSON), and then use the keys to pull the data. Since it's in an array, you'll have to use [0] to pull the first item in the array (ie: your data).
Example
$(document).ready(function(){
var j ='[{"ErrorMessage":"","ID":294,"ExpenseID":0,"EffectiveDate":"/Date(1262284200000)/","FormattedEffectiveDate":"01-01-2010","Perunit":null,"VATRate":17.5,"ChangedByID":1,"ChangedByName":"superuser, superuser","Expense":null,"ErrorSummary":null,"ErrorList":[]}]';
var json = $.parseJSON(j);
alert("VATRate: "+json[0].VATRate);
});
Fiddle for reference
I have the following JSON value pushed from the server.
result=[{"id":1492,"name":"Delhi"},
{"id":109,"name":"Coimbatore"},
{"id":576,"name":"Konni"},
{"id":525,"name":"Kottayam"}
]
I know how to convert JSON Array to Javascript Array.Here is the code below(got from stackoverflow)
var locations = [];
$.each(result, function(i, obj) {
locations.push([obj.id,obj.name]);
});
I want to convert this JSON Array to a JavaScript Object Array so that I can access the values as jarray[0].id which will give me the value 1492. Please advice
You don't need to do anything to the result array. Just use result[0].id and it will evaluate to 1492.