Results 1 to 18 of 18

Thread: [RESOLVED] getting values from string

  1. #1

    Thread Starter
    Member
    Join Date
    Oct 2021
    Posts
    38

    Resolved [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.

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    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;
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  3. #3

    Thread Starter
    Member
    Join Date
    Oct 2021
    Posts
    38

    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

  4. #4
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    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);
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  5. #5

    Thread Starter
    Member
    Join Date
    Oct 2021
    Posts
    38

    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.

  6. #6
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    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.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  7. #7

    Thread Starter
    Member
    Join Date
    Oct 2021
    Posts
    38

    Re: [RESOLVED] getting values from string

    dday9, thanks
    Last edited by UserBee; Oct 26th, 2021 at 08:08 PM.

  8. #8

    Thread Starter
    Member
    Join Date
    Oct 2021
    Posts
    38

    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?

  9. #9
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    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:
    1. The JSON literal is empty
    2. The JSON literal cannot be parsed to an object
    3. The root element does not have a destinations key
    4. The destinations element is not an array
    5. 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.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  10. #10
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    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?

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  11. #11
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    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.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  12. #12

    Thread Starter
    Member
    Join Date
    Oct 2021
    Posts
    38

    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>

  13. #13
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    Re: [RESOLVED] getting values from string

    You shouldn’t be using else ifs like that.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  14. #14

    Thread Starter
    Member
    Join Date
    Oct 2021
    Posts
    38

    Re: [RESOLVED] getting values from string

    Quote Originally Posted by dday9 View Post
    You shouldn’t be using else ifs like that.
    may I ask why ?

  15. #15

    Thread Starter
    Member
    Join Date
    Oct 2021
    Posts
    38

    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>

  16. #16

    Thread Starter
    Member
    Join Date
    Oct 2021
    Posts
    38

    Re: [RESOLVED] getting values from string

    I still having issues on empty result
    Last edited by UserBee; Nov 3rd, 2021 at 06:40 PM.

  17. #17
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    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.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  18. #18

    Thread Starter
    Member
    Join Date
    Oct 2021
    Posts
    38

    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
  •  



Click Here to Expand Forum to Full Width