-
Oct 25th, 2021, 10:23 PM
#1
Thread Starter
Member
[RESOLVED] getting values from string
I have this string below as follows :
Code:
{"code":"Ok","distances":[[0,125891.8],[126454.6,0]],"sources":[{"hint":"k9mxjU3asY0IAAAAAAAAAPIBAAAzAAAAdD6TQQAAAABTIIpEaW7lQggAAAAAAAAA8gEAADMAAAAD5QAAZQOlAF2A_AIoCqUA1Hv8Ak0ADw5L-_pG","distance":178.886682,"location":[10.814309,50.102365],"name":""},{"hint":"7rGhiTqyoYkLAAAAHgAAAE8AAABOAQAA--7QQf_ig0INMTJDfe05RAsAAAAeAAAATwAAAE4BAAAD5QAAROS2AEVI9wKk5LYA6kb3AgcAPxBL-_pG","distance":39.209625,"location":[11.985988,49.760325],"name":""}],"destinations":[{"hint":"k9mxjU3asY0IAAAAAAAAAPIBAAAzAAAAdD6TQQAAAABTIIpEaW7lQggAAAAAAAAA8gEAADMAAAAD5QAAZQOlAF2A_AIoCqUA1Hv8Ak0ADw5L-_pG","distance":178.886682,"location":[10.814309,50.102365],"name":""},{"hint":"7rGhiTqyoYkLAAAAHgAAAE8AAABOAQAA--7QQf_ig0INMTJDfe05RAsAAAAeAAAATwAAAE4BAAAD5QAAROS2AEVI9wKk5LYA6kb3AgcAPxBL-_pG","distance":39.209625,"location":[11.985988,49.760325],"name":""}]}
I wanted to get all the values between the words "distance" and "location" on the section destinations.
Please kindly assist me on the code.
-
Oct 26th, 2021, 09:49 AM
#2
Re: getting values from string
Your string is actually JSON. You can parse the JSON literal to an object using JSON.parse (documentation). Then you would simply access the respective member of the object:
Code:
const literal = '{"code":"Ok","distances":[[0,125891.8],[126454.6,0]],"sources":[{"hint":"k9mxjU3asY0IAAAAAAAAAPIBAAAzAAAAdD6TQQAAAABTIIpEaW7lQggAAAAAAAAA8gEAADMAAAAD5QAAZQOlAF2A_AIoCqUA1Hv8Ak0ADw5L-_pG","distance":178.886682,"location":[10.814309,50.102365],"name":""},{"hint":"7rGhiTqyoYkLAAAAHgAAAE8AAABOAQAA--7QQf_ig0INMTJDfe05RAsAAAAeAAAATwAAAE4BAAAD5QAAROS2AEVI9wKk5LYA6kb3AgcAPxBL-_pG","distance":39.209625,"location":[11.985988,49.760325],"name":""}],"destinations":[{"hint":"k9mxjU3asY0IAAAAAAAAAPIBAAAzAAAAdD6TQQAAAABTIIpEaW7lQggAAAAAAAAA8gEAADMAAAAD5QAAZQOlAF2A_AIoCqUA1Hv8Ak0ADw5L-_pG","distance":178.886682,"location":[10.814309,50.102365],"name":""},{"hint":"7rGhiTqyoYkLAAAAHgAAAE8AAABOAQAA--7QQf_ig0INMTJDfe05RAsAAAAeAAAATwAAAE4BAAAD5QAAROS2AEVI9wKk5LYA6kb3AgcAPxBL-_pG","distance":39.209625,"location":[11.985988,49.760325],"name":""}]}';
const parsedObject = JSON.parse(literal);
const distances = parsedObject.distances;
-
Oct 26th, 2021, 05:56 PM
#3
Thread Starter
Member
Re: getting values from string
dday9, yes it is a json string and thanks for your reply. I will just post beautified json string below. I see in your code that you used distances section. but actually i will be needing the destination section and getting all the distance values. can you kindly help me further with the code. I dont know much of json parsing yet but surely I will read that documentation. right now I just need to finish the code. TIA
Code:
{
"code": "Ok",
"distances": [
[0, 125891.8],
[126454.6, 0]
],
"sources": [{
"hint": "nhecjfsXnI0IAAAAAAAAAPIBAAAzAAAAdD6TQQAAAABTIIpEaW7lQggAAAAAAAAA8gEAADMAAAAk5QAAZQOlAF2A_AIoCqUA1Hv8Ak0ADw7qZper",
"distance": 178.886682,
"location": [10.814309, 50.102365],
"name": ""
}, {
"hint": "pnKwifJysIkLAAAAHgAAAE8AAABOAQAA--7QQf_ig0INMTJDfe05RAsAAAAeAAAATwAAAE4BAAAk5QAAROS2AEVI9wKk5LYA6kb3AgcAPxDqZper",
"distance": 39.209625,
"location": [11.985988, 49.760325],
"name": ""
}],
"destinations": [{
"hint": "nhecjfsXnI0IAAAAAAAAAPIBAAAzAAAAdD6TQQAAAABTIIpEaW7lQggAAAAAAAAA8gEAADMAAAAk5QAAZQOlAF2A_AIoCqUA1Hv8Ak0ADw7qZper",
"distance": 178.886682,
"location": [10.814309, 50.102365],
"name": ""
}, {
"hint": "pnKwifJysIkLAAAAHgAAAE8AAABOAQAA--7QQf_ig0INMTJDfe05RAsAAAAeAAAATwAAAE4BAAAk5QAAROS2AEVI9wKk5LYA6kb3AgcAPxDqZper",
"distance": 39.209625,
"location": [11.985988, 49.760325],
"name": ""
}]
}
Last edited by dday9; Oct 26th, 2021 at 05:57 PM.
Reason: Added code tags
-
Oct 26th, 2021, 05:59 PM
#4
Re: getting values from string
Since destinations is an array, what you would do is loop over the array to get the currently iterated item's distance property. You don't need to manually loop through them, rather you can use the map operator:
Code:
const distances = parsedObject.destinations.map(destination => destination.distance);
console.log(distances);
-
Oct 26th, 2021, 06:02 PM
#5
Thread Starter
Member
Re: getting values from string
wow. now I appreciated json string more. thank you very much dday9. You are very helpful. I cant thank you enough sincerely. God bless.
-
Oct 26th, 2021, 06:16 PM
#6
Re: [RESOLVED] getting values from string
Yeah, while JSON is a text format that is completely language independent, it was based on a subset of the JavaScript language.
So manipulating/querying JSON from JavaScript goes together very nicely.
-
Oct 26th, 2021, 07:44 PM
#7
Thread Starter
Member
Re: [RESOLVED] getting values from string
Last edited by UserBee; Oct 26th, 2021 at 08:08 PM.
-
Oct 28th, 2021, 05:16 AM
#8
Thread Starter
Member
Re: [RESOLVED] getting values from string
@dday9, there are times that the result is empty, how is that happening or what can i do to catch it the error?
-
Oct 28th, 2021, 08:40 AM
#9
Re: [RESOLVED] getting values from string
There are a couple of places where it could fail. If you expect the JSON to change then you can setup conditional statements to catch where it is failing. These places would be:
- The JSON literal is empty
- The JSON literal cannot be parsed to an object
- The root element does not have a destinations key
- The destinations element is not an array
- The destinations element is empty
Take a look at this function which provides a bit more error handling:
Code:
const getDistances = (input) => {
let parsedObject = {};
try {
parsedObject = JSON.parse(input);
} catch (e) {
console.error('The incoming JSON literal is not valid.');
return null;
}
if (typeof parsedObject !== "object") {
console.error('The incoming JSON is not a valid object.');
return null;
}
if (Object.keys(parsedObject).indexOf('destinations') < 0) {
console.error('The incoming JSON does not have a destinations property.');
return null;
}
if (!Array.isArray(parsedObject.destinations)) {
console.error('The incoming JSON\'s destinations property is not a valid array.');
return null;
}
if (parsedObject.destinations.length < 0) {
console.error('The incoming JSON\'s destinations property is empty.');
return null;
}
return parsedObject.destinations.map(destination => destination.distance);
}
Fiddle: https://jsfiddle.net/yt3dagpk/
With this function, if anything but an array is returned then you know that the JSON was not formatted properly. If you get back an empty array then you know that there were no distance values in the destinations array.
-
Oct 28th, 2021, 09:15 AM
#10
Re: [RESOLVED] getting values from string
@dday9 - you just exposed me to some syntax that I do not use in JS - the CONST keyword and => arrow function definition.
Now I've just completed watching half a dozen videos in a series that explains this newer ES8 syntax, along with PROMISES and ASYNC/AWAIT!
Do you find that some browsers choke at this new syntax, or are all browsers at this point at this rev level?
-
Oct 28th, 2021, 09:35 AM
#11
Re: [RESOLVED] getting values from string
I believe arrow functions work great in every browser except IE where I don't think that they work at all.
The const and let declarations work in every browser, but there's a caveat to IE. While they are valid keywords, they don't work like they're supposed to. These declaration keywords were meant to address the way that JavaScript implements hoisting by confining the declaration to the scoped block in which its declared. This works great in every browser, but in IE it will not work in loops, which is pretty much every situation where I've run into hoisting issues, making it pretty much useless in IE.
I've not really worked with async/await yet because most of my JavaScript now is actually TypeScript via Angular. And the promise pattern Angular usually follows is an observable one. So I can't really say with async/await.
Long story short, IE sucks.
-
Oct 28th, 2021, 07:09 PM
#12
Thread Starter
Member
Re: [RESOLVED] getting values from string
I modified it to my need like below but there are still instances of empty result.
Code:
<script>
var distances;
var parsedObject;
var a;
function init()
{
txt=document.body.innerText;
const literal = txt;
let parsedObject = {};
try
{
parsedObject = JSON.parse(literal);
}
catch (e)
{
parsedObject = null;
}
if (typeof parsedObject !== "object")
{
distances = 0;
}
else if (Object.keys(parsedObject).indexOf('destinations') < 0)
{
distances = 0;
}
else if (!Array.isArray(parsedObject.destinations))
{
distances = 0;
}
else if (parsedObject.destinations.length < 0)
{
distances = 0;
}
else
{
distances = parsedObject.destinations.map(destination => destination.distance);
}
document.body.innerText = distances;
}
</script>
-
Oct 28th, 2021, 07:26 PM
#13
Re: [RESOLVED] getting values from string
You shouldn’t be using else ifs like that.
-
Oct 28th, 2021, 07:48 PM
#14
Thread Starter
Member
Re: [RESOLVED] getting values from string
Originally Posted by dday9
You shouldn’t be using else ifs like that.
may I ask why ?
-
Oct 28th, 2021, 08:14 PM
#15
Thread Starter
Member
Re: [RESOLVED] getting values from string
modified my code to below but still there are instances of blank / empty results. i already disabled the timeout limit of php curl execution.
Code:
<script>
var distances;
var parsedObject;
var a;
function init()
{
txt=document.body.innerText;
const literal = txt;
let parsedObject = {};
try
{
parsedObject = JSON.parse(literal);
}
catch (e)
{
parsedObject = null;
}
if ((typeof parsedObject !== "object") || (Object.keys(parsedObject).indexOf('destinations') < 0) || (!Array.isArray(parsedObject.destinations)) || (parsedObject.destinations.length < 0) )
{
distances = 0;
}
else
{
distances = parsedObject.destinations.map(destination => destination.distance);
}
document.body.innerText = distances;
}
</script>
-
Nov 3rd, 2021, 05:49 PM
#16
Thread Starter
Member
Re: [RESOLVED] getting values from string
I still having issues on empty result
Last edited by UserBee; Nov 3rd, 2021 at 06:40 PM.
-
Nov 4th, 2021, 09:58 AM
#17
Re: [RESOLVED] getting values from string
I apologize, but if you follow the code that I gave in post 9, the only way that you'd have an empty array was if destinations was empty. Otherwise, if any other condition failed to meet the specific business logic, then null would be returned and you would know that the data is not in the correct format.
-
Nov 4th, 2021, 06:10 PM
#18
Thread Starter
Member
Re: [RESOLVED] getting values from string
I found the problem dday. It was the resulting output of curl that lacking backslash that is why there is Null in this point parsedObject = null;
Thanks. Moving on.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|