Get values from JSON returned data - javascript

So I have a function that makes an ajax call and returns a json string. I am having trouble trying to access the values that I need, below is my code of what I have and a few examples of what I have tried.
s.search().then(function (specials) {
var returnJSON = JSON.parse(specials[0]);
var x = returnJSON.location.x;
var y = returnJSON.location.y;
});
When I check the dev tools I'm getting the following error.
JSON.parse: unexpected character at line 1 column 2 of the JSON data
Here is the the JSON returned value after I stringify it.
[{"feature":{"geometry":{"type":"point","x":-82.9172080701955,"y":42.55426092899978,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Postal","Match_addr":"48035, Clinton Township, Michigan","StAddr":"","City":"Clinton Township","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-82.922209,"ymin":42.549261,"xmax":-82.912209,"ymax":42.559261,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"48035, Clinton Township, Michigan"},{"feature":{"geometry":{"type":"point","x":-84.03589825899667,"y":44.826904141314174,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.085899,"ymin":44.776904,"xmax":-83.985899,"ymax":44.876904,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-83.93987906956261,"y":42.065412162742234,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-83.98988,"ymin":42.015412,"xmax":-83.88988,"ymax":42.115412,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-82.93354923650725,"y":42.60054198222781,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-82.98355,"ymin":42.550542,"xmax":-82.88355,"ymax":42.650542,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-83.97095926895429,"y":42.07240087260328,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton, Michigan","StAddr":"","City":"Clinton","score":94.29},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.02096,"ymin":42.022401,"xmax":-83.92096,"ymax":42.122401,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton, Michigan"},{"feature":{"geometry":{"type":"point","x":-84.6015125489642,"y":42.943655651388326,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"SubAdmin","Match_addr":"Clinton, Michigan","StAddr":"","City":"Clinton","score":94.29},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.839514,"ymin":42.705656,"xmax":-84.363514,"ymax":43.181656,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton, Michigan"}]
I am trying to access candidates location x value and y value.

There are some Strings in your JSON on separate lines. When you copy and paste your JSON in a linter (e.g.: json linter), you will see the errors.
EDIT:
You edited your question so you are now using valid JSON.
There is no need to parse your JSON when you already have valid JSON. You can just select the correct keys. Looking at your JSON, you can select your x and y like this:
var returnJSON = specials[0];
var x = returnJSON.feature.geometry.x;
var y = returnJSON.feature.geometry.y;
Checkout this codepen for an example.

You don't need to "parse" JSON returned from a service usually. It is already a Javascript object in the then callback.
s.search().then(function (specials) {
var firstItem = specials[0];
var x = firstItem.location.x;
var y = firstItem.location.y;
});
It should be noted, however, that the first item that comes back in your array of specials does not have a property location accoring to the JSON example you posted.
Perhaps you were after firstItem.feature.geometry.x, but im not sure.

Related

How to modify text in Javascript

I made a script to retrieve data from an API and show it in HTML.
The problem is that the API answers with something like that
[{"seen":"2021-08-24 04:13:51"}]
And I want the user to see something like
2021-08-24 04:13:51
How can i modify this text inside of javascript? (The output is variable but the number of characters is always the same, idk if this is a useful info...)
What you have to do is set innerText value from the JSON. You can access the value using response[0].seen
const response = [{"seen":"2021-08-24 04:13:51"}];
console.log(response[0].seen);
document.getElementById('lastupdatedon').innerText = response[0].seen;
<p id="lastupdatedon"></p>
The server is returning data in json format, you need to parse the response to a javascript object and then you can use the value as you want
const theServerResponse = '[{"seen":"2021-08-24 04:13:51"}]'
const parsedResponse = JSON.parse(theServerResponse)
//At this point you can get that value
parsedResponse[0].seen
Use below script
var fromAPI='[{"seen":"2021-08-24 04:13:51"}]';
var data=JSON.parse(fromAPI);
if(data!=null && data.length>0)
{
document.getElementById('lastupdatedon').innerText = data[0].seen;
}
HTML
<h3 id="lastupdatedon"></h3>
Do not forget to check for nulls, index is greater than 0. IF server doesnt return data then your app will throw an error of undefined.

How do I access a JSON array in JavaScript

I have a PHP script to which I make an Ajax request, and most of it works okay, but I'm having trouble accessing an array in the data returned to the JavaScript function.
So, the PHP has a bunch of regular variables, and one array. The array, $places, has four elements, which each have three values, as so:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
A relevant excerpt of the PHP script is:
$encoded_places = json_encode($places); // if I don't do this then I end up with a value of "Array"
$qobject->name = "$name";
$qobject->multi = "$multi";
$qobject->places= "$encoded_places";
$myJSON = json_encode($qobject);
echo $myJSON;
In the JavaScript script (using JQuery), I successfully obtain the data from the Ajax request, and I can access all the data okay, except the $places data.
$.getJSON(url, function(data, status){
var stringified = JSON.stringify(data);
var parsedObj = JSON.parse(stringified);
var x = parsedObj.name; // alert(x); // which works fine
var myArray = new Array();
myArray.push(parsedObj.places);
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
}
... and the console will display what I'm expecting, namely:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
However, I'm having difficulty accessing these values. For example, supposing I try to access the "815" portion of the first element, with something like: myArray[0][1], all I end up with is "[".
I guess somehow this whole piece of data is just a string, instead of an array, but I'm not familiar enough with JavaScript to quite know how to progress.
If, for example, I do this in the JavaScript script (hoping to see 815, 2813, 1582 and 1220 in the alerts) all I'll see is the single alert with "[". (i.e. it does the loop only once, and selects the character in position 1).
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
alert(myArray[i][1]);
}
I would very much appreciate someone explaining:
(a) how I can access the individual elements and values in JS
(b) how I can loop through them, although presumably once it's an array and not a string then the code above should do this.
Many thanks for any assistance.
Now Resolved:
As noted by #charlietfl, below, using quotes in
$qobject->places= "$encoded_places";
screwed things up, along with using json_encode on $places. However, without removing the quotes nothing worked either way. So, removed quotes and just used json_encode on the entire structure at the end, which now works fine.
So, the original snippet of code, given above, now looks like:
$qobject->name = $name;
$qobject->multi = $multi;
$qobject->places= $places;
$myJSON = json_encode($qobject);
echo $myJSON;
Change
$qobject->places = "$encoded_places";
To
$qobject->places = $places;
And get rid of the $encoded_places = json_encode($places); so that the one call to json_encode serializes the whole structure
Try this:
$.getJSON(url, function(data, status){
var parsedObj = JSON.parse(stringified);
console.table(parsedObj.places);
console.log(parsedObj.places)[0][0];
}
In the posted code's getJSON context, data is already a JSON string. So this line is redundantly stringifying your JSON string:
var stringified = JSON.stringify(data);
stringified is now set to a literal/escaped version of the valid JSON string from the data parameter:
[[\"z\",\"815\",\"1\"],[\"w\",\"2813\",\"0\"],[\"s\",\"1582\",\"2\"],[\"b\",\"1220\",\"5\"]]
When that double-stringified value is passed to JSON.parse for the parsedObj reference, it just becomes the original JSON string again (which looks deceptively correct in an alert box).
Strings are iterable in JavaScript, so the for loop was just going over the string.

How to store and retrieve JSON data into local storage?

I have this code:
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
This code will use localStorage.
Here is now the code to get the stored data:
var retrievedObject = localStorage.getItem('added-items');
My problem now is, how can i get the size of the data items? answer must be 2.
How can i get the "Item1" and "Item2"?
I tried retrievedObject[0][0] but it is not working.
And how to add data on it?
so it will be
{"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
Can I use JSON.stringify?
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
stringify means, take an object and return its presentation as a string.
What you have, is already a string and not a JSON object.
The opposite is JSON.parse which takes a string and turns it into an object.
Neither of them have anything to do with getting the size of an array. When properly coding JavaScript you almost never use JSON.parse or JSON.stringify. Only if serialization is explicitly wanted.
Use length for the size of the array:
var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
console.debug(obj.items.length);
// THIS IS ALREADY STRINGIFIED
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
// DO NOT STRINGIFY AGAIN WHEN WRITING TO LOCAL STORAGE
localStorage.setItem('added-items', string);
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('added-items');
// CONVERT STRING TO REGULAR JS OBJECT
var parsedObject = JSON.parse(retrievedObject);
// ACCESS DATA
console.log(parsedObject.items[0].Desc);
To bring clarity to future people that may stumble across this question and found the accepted answer to not be everything you hoped and dreamed for:
I've extended the question so that the user may either want to input a string or JSON into localStorage.
Included are two functions, AddToLocalStorage(data) and GetFromLocalStorage(key).
With AddToLocalStorage(data), if your input is not a string (such as JSON), then it will be converted into one.
GetFromLocalStorage(key) retrieves the data from localStorage of said key
The end of the script shows an example of how to examine and alter the data within JSON. Because it is a combination of objects and array, one must use a combination of . and [] where they are applicable.
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};
localStorage.setItem('added-items', AddToLocalStorage(string));
localStorage.setItem('added-items', AddToLocalStorage(json));
// this function converts JSON into string to be entered into localStorage
function AddToLocalStorage(data) {
if (typeof data != "string") {data = JSON.stringify(data);}
return data;
}
// this function gets string from localStorage and converts it into JSON
function GetFromLocalStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
var myData = GetFromLocalStorage("added-items");
console.log(myData.items[2].firstName) // "John"
myData.items[2].firstName = ["John","Elizabeth"];
myData.items[2].lastName = ["Smith","Howard"];
console.log(myData.items[2]) // {"firstName":["John","Elizabeth"],"lastName":["Smith","Howard"]}
console.log(myData.items.length) // 4
JSON.parse is definitely the best way to create an object but I just want to add if that doesn't work (because of lack of support), obj = eval('(' + str + ')'); should work. I've had a problem with a HTML to PDF converter in the past that didn't include JSON.parse and eval did the trick. Try JSON.parse first.
Access your object: obj.items[0].Desc;
var object = Json.parse(retrievedObject);
Now you can access it just like an array
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you need more help i have some previous code where i am reading Json from local storage and making a form from that json. This code will help in understanding how to traverse that array
Json stored in localstorage
{"form":[{"element":"input", "type":"text","name":"name","value":"value","min":"2","max":"10"}]}
JavaScript to read that json
function readJson(){
if(!form_created){
add_form();
}
var fetched_json = localStorage.getItem("json");
var obj=JSON.parse(fetched_json);
for(var i=0; i<obj.form.length;i++){
var input = document.createElement(obj.form[i].element);
input.name = obj.form[i].name;
input.value = obj.form[i].value;
input.type = obj.form[i].type;
input.dataset.min = obj.form[i].min;
input.dataset.max = obj.form[i].max;
input.dataset.optional = obj.form[i].optional;
form.insertBefore (input,form.lastChild);
}
alert(obj.form[0].name);
}

How to properly decode a JSON string encoded using Html.Raw(Json.Encode(Model))?

I am encoding some model data into a html element like this:
#Html.Raw(Json.Encode(Model));
The json string returned looks like this:
{"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo":8314,"TSeqNoSpecified":true,"TestDescr":"HBsAg"},{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6124","SeqNo":9295,"SeqNoSpecified":true,"TSeqNo":8315,"TSeqNoSpecified":true,"TestDescr":"HCV Ab"},{"FrequencyType":"1X","GCDs":"585.3","Identifier":"6","SeqNo":9729,"SeqNoSpecified":true,"TSeqNo":8309,"TSeqNoSpecified":true,"TestDescr":"HD Monthly LS"}],"Frequency":[{"Key":"ANNUAL","Value":"Annually"},{"Key":"BIMONTH","Value":"Bi-Monthly"},{"Key":"BIWEEK","Value":"Bi-Weekly"},{"Key":"MON","Value":"Monthly"},{"Key":"1X","Value":"One Time"},{"Key":"QTR","Value":"Quarterly"},{"Key":"SMAN","Value":"Semi-Annual"},{"Key":"WEEK","Value":"Weekly"}]};
When I try to parse this using JSON.parse, I get an error:
arrayTestList = [];
var jsonTestList = $('#TestList').text();
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]); // <===== this line is failing
Unable to get value of the property '0': object is null or undefined
How do I convert this jsonTestList string into a javascript array so that I can access elements of arrayTestList properly?
Edit:
Sorry, I forgot to mention my edit. Basically above javascript code is inside a Partial View 2. The code where I am json encoding the model is in another Partial View 1. From P V 2, I cannot access the model object of P V 1, so I am just dumping the contents into a div tag, so that I can access this list TestList element.
Try removing this line:
jsonTestList = JSON.stringify(jsonTestList);
jsonTestList is already a JSON string
The issue is now resolved.
I was getting an invalid character, but couldn't immediately recognize which character it was that was causing the problem. I found that my JSON string isn't valid because of the trailing semicolon that was output by the Json.Encode method. I validated the JSON string # http://jsonlint.com.
Once I removed that semicolon, the json string is populated as a JavaScript array into arrayTestList object.
Now just this works, as mentioned in both the answers above, JSON.stringify is not needed.
var arrayTestList = [];
var jsonTestList = $('#TestList').text().replace(";","");
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]);
Why are you using Json.Encode? Also in your code, why are you writing redundant code first you are using JSON.stringify and the JSON.parse same object.
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
As per my understanding just Html.Raw will work
In JavaScript
var jsonObject = #Html.Raw(Model.TestList); //Here you will get JavaScript Object
var jsonTestList = jsonObject.TestList;

convert an input value in array

I have this data in an input: [16,57.35], [23,56.26], [34,54.57]
and I want to turn it into an array
var data =$('#data').val();
var array = JSON.parse ("["+data+"]");
I'm having this error
Uncaught SyntaxError: Unexpected token.
How I can fix it or I can convert the input value in array?
Your code is working check it here, you may need to include required jQuery library or check some thing else in the code causing it.
data = $('#txt1').val();
arr = JSON.parse ("["+data+"]");
console.log(arr);
Try using the eval function:
var data = "123, 456, 789";
var array = eval("[" + data + "]");
You'll need to make sure that whatever you're inputting is valid JSON, but the above code will output an array for you. Hope it helps.

Categories