Javascript - How to access JSON array of objects - javascript

I'm starting with JSON/Ajax development with Javascript and right now I have a scenario where I'm receiving a JSON string from the server and I want to build an object on the client side.
My server output is this:
[{"username":"user","mine":"[{"id":"1","artist":"Pearl Jam","name":"Rival"},{"id":"2","artist":"Pearl Jam","name":"Lukin"}]","default":"50"}]
On the JS side I'm doing this:
$.getJSON('?action=load',
function(data)
{
window.User = data[0];
});
I can print window.User.username and window.User.default. However I was expecting I could do something like alert(window.User.mine[0].id) as well, but it prints [ (the first character of the songs array, so I'm assuming it is being interpreted as a string).
What I'm I doing wrong here?
Thanks a lot in advance.

"[{"id":"1","artist":"Pearl Jam","name":"Rival"},{"id":"2","artist":"Pearl Jam","name":"Lukin"}]"
should be this
[{"id":"1","artist":"Pearl Jam","name":"Rival"},{"id":"2","artist":"Pearl Jam","name":"Lukin"}]
The quotes around the arrays make them strings

Your JSON is malformed, so you get a string and not an array, thats the reason.
Your JSON should look like this:
[{"username":"user","mine":[{"id":"1","artist":"Pearl Jam","name":"Rival"},{"id":"2","artist":"Pearl Jam","name":"Lukin"}],"default":"50"}]
and then you will get the expected result

Use:
window.User.mine.[0].id
(after fixing your JSON as suggested...)

Related

How do I parse part of a JSON object that has mixed string and numbers?

I have a JSON file that was processor generated with lines like this
jsonData: "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}"
I can target the 'jsonData' object but that returns everything within the double quotes as a string.
I tried ...dataset[0].jsonData[8] which returns the '3' from the first value. I guess I could throw the mixed strings into a JS function and use regex to remove the extra stuff, but thats probably the hackyest way to do this.
Whats the easiest way to target the values only?
If you want to interact with it like the list I would consider something like
var list = jsonData.split("[")[1].split("]")[0].split(",")
Console.log(list);
The console reads:
[
'350.23', '250.32',
'150.34', '340.50',
'236.70', '370.45',
'380.55'
]
From here you can use list[3] to get 340.50
If you don't want to spend the time fixing your JSON just do this:
let values = "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}".split(',').map(_ => _.replace(/[^0-9.]/g,''))
console.log(values)

How to convert a string to JSON format?

I was getting list in array form. So at first place i converted array list to string-
var myJsonString = JSON.stringify(result);
myJsonString="[{"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
},
{"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
}]"
But again i need to convert myJsonString to Json format, What i need to do? I mean i need to replace 1st" and last ", I guess
You need to call parse now.
JSON.parse(myJsonString)
First, if you ever find yourself building a JSON string by concatenating strings, know that this is probably the wrong approach.
I don't really understand how the first line of your code relates to the second, in that you are not doing anything with JSON-encoded string output from result, but instead just overwriting this on the following line.
So, I am going to limit my answer to show how you could better form JSON from an object/array definition like you have. That might look like this:
// build data structure first
// in this example we are using javascript array and object literal notation.
var objArray = [
{
"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
},{
"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
}
];
// now that your data structure is built, encoded it to JSON
var JsonString = JSON.stringify(objArray);
Now if you want to work with JSON-encoded data, You just do the opposite:
var newObjArray = JSON.parse(JsonString);
These are really the only two commands you should ever use in javascript when encoding/decoding JSON. You should not try to manually build or modify JSON strings, unless you have a very specific reason to do so.

Handle Data returned by POST request in Javascript

I have a PHP script - it returns a file like this after POSTing to it with the help of $.post() using jQuery.
13.0519 77.5416
13.028 77.5409
12.9787 77.5724
12.9317 77.6227
How do I go through the lines of data returned in the $.post().done(function(data){}) in Javascript ?
You can split returned text by newline character and then loop over resulting array of lines, probably splitting one more time by space to get array of numbers:
$.post(/*...*/).done(function(data) {
var lines = data.split(/\n/);
lines.forEach(function(line) {
console.log(line.split(' '));
});
});
The best way is to have PHP return JSON (with an array of these).
If not possible, however, then you can get the string and split it on new lines, to achieve a similar effect. Something along the lines of
var arrayOfResults = postData.split("\n");
Then just iterate and do whatever is needed.

How to convert the json results to array using javascript?

I need to convert the Json response to array using JavaScript .
I have the json response which is :
["simmakkal madurai","goripalayam madurai"].
now I want to change this results to array format .
So, How to I convert the json result to array.
Try this :-
var obj = $.parseJSON('["simmakkal madurai","goripalayam madurai"]');
If you alert(obj[0]), you will get answer as simmakkal madurai
var arr = JSON.parse('["simmakkal madurai","goripalayam madurai"]');
Yeah,
if your response is
var res = '["simmakkal madurai","goripalayam madurai"]';
Then you just need to do
var arr = JSON.parse(res);
Alternativly you could do an eval but evals are never realy recommended, but since you are going from server side to client side (php -> javascript) it wouldnt the the worst thing.
Anyways JSON.parse should work

create javascript array in json response in Java

I have a servlet where I send JSON response (back to javascript) . For example , my response looks like
{
"responseStr":"1,5,119.8406677,7,7,116.5664291,10,10,116.6099319,20,10,117.2185898,25,3,115.2636185"
}
Now what is happening at the moment is that I am collecting data( numbers above) in servlet and sending it in JSON response as a String with comma separated values. When this response reaches front end, all these numbers have to go in a javascript array (where I do my further logic). Currently I am doing this by
var res = JSON.parse(REQ.responseText);
var myArr = res.responseStr.split(',');
My thinking is that the second line( where I use split()) is causing a bottleneck in my application . A few data points as in above example are not a trouble but it becomes a problem when i have thousands of data points.
So my question is that is there a way that when I am creating my response in servlet that I can create the response as javascript array so that I do not have to use split() at all?
Any better ways of achieving the above task of converting the response into javascript array?
If you send responseStr as an Array, when the JSON parses it, it will be an array. So you could send your JSON response as "[1,2,3,4,5,6,7]" and so one, and when you JSON.parse, it will return an array.
To make it a little more clear :
var arr = [1,2,3,4,5];
arr = JSON.stringify(arr); // "[1,2,3,4,5]" -- String
arr = JSON.parse(arr); // [1,2,3,4,5] -- Array
In your response set content-type JSON/application and send JSON array
{
"responseStr":["1","5","119.8406677","7","7","116.5664291","10","10","116.6099319","20","10","117.2185898","25","3","115.2636185"]
}
Then in your JavaScript you can simply use (reference):
var myArray = responseJSONObject.responseStr;
You may utilize JSON.js for various tasks.
That is a great question. JSON can return an array as simply as
{ "responseStr": [[1], [2], [3], [4] }
Cool!
Double Quotes are not necessary unless you want them as strings.
One more thing, you can have multi dimensional arrays too!
{ "responseStr": [[1,10], [2,20], [3,30], [4,40]] }
This link is a great reference:
http://json.org/fatfree.html

Categories

Resources