Issues parsing a JSON file from a database into JavaScript - javascript
I have created an SQL database using PHPmyAdmin which stores JSON files, the idea is to use these files with the Google Maps API to place markers on a map.
I am having trouble converting the JSON file to a JavaScript Object.
after retrieving the json from the database and converting it to a JS format, i assigned it to a variable.
For display purposes I have shown the way I get the String from PHP:
var jsonString ='<?php echo implode(" ", $firstJsonString); ?>'
As well as the actual string:
var jsonString = '{"address_components":[{"long_name":"London","short_name":"London","types":["locality","political"]},{"long_name":"London","short_name":"London","types":["postal_town"]},{"long_name":"Greater London","short_name":"Greater London","types":["administrative_area_level_2","political"]},{"long_name":"England","short_name":"England","types":["administrative_area_level_1","political"]},{"long_name":"United Kingdom","short_name":"GB","types":["country","political"]}],"adr_address":"<span class="locality">London</span>, <span class="country-name">UK</span>","formatted_address":"London, UK","geometry":{"location":{"lat":51.5073509,"lng":-0.12775829999998223},"viewport":{"south":51.38494009999999,"west":-0.351468299999965,"north":51.6723432,"east":0.14827100000002247}},"icon":"https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png","id":"b1a8b96daab5065cf4a08f953e577c34cdf769c0","name":"London","photos":[{"height":800,"html_attributions":["Edu Sousa"],"width":1200},{"height":1065,"html_attributions":["Manuel Ligabue"],"width":1600},{"height":1365,"html_attributions":["David Sun"],"width":2048},{"height":2136,"html_attributions":["Nuno Martins"],"width":3216},{"height":3000,"html_attributions":["Roberto Gerosa"],"width":4000},{"height":3024,"html_attributions":["ALLWYN D'SILVA"],"width":4032},{"height":1080,"html_attributions":["Cristina Cunsolo"],"width":1920},{"height":1362,"html_attributions":["Dendy Legends"],"width":2048},{"height":1440,"html_attributions":["Destiny Symonee"],"width":2560},{"height":1452,"html_attributions":["Leslie"],"width":5248}],"place_id":"ChIJdd4hrwug2EcRmSrV3Vo6llI","reference":"CmRbAAAAw49v9euZCWzrvjJ9b8STdg4qK48YueqQIOMerhQ43OP-NynPqFygwZnFzb-jcKkRKJog7z2IeUubF468akLhMj7pIZSoOWFXGjKC0WgkubgTIRlySRkBM47V9RMcX5YoEhB3qYHCQ3roB1G_gHnh_i8MGhSbxmofinNGCLquqddTEQ3DjsKOcg","scope":"GOOGLE","types":["locality","political"],"url":"https://maps.google.com/?q=London,+UK&ftid=0x47d8a00baf21de75:0x52963a5addd52a99","utc_offset":60,"vicinity":"London","html_attributions":[]} {"address_components":[{"long_name":"London","short_name":"London","types":["locality","political"]},{"long_name":"London","short_name":"London","types":["postal_town"]},{"long_name":"Greater London","short_name":"Greater London","types":["administrative_area_level_2","political"]},{"long_name":"England","short_name":"England","types":["administrative_area_level_1","political"]},{"long_name":"United Kingdom","short_name":"GB","types":["country","political"]}],"adr_address":"<span class="locality">London</span>, <span class="country-name">UK</span>","formatted_address":"London, UK","geometry":{"location":{"lat":51.5073509,"lng":-0.12775829999998223},"viewport":{"south":51.38494009999999,"west":-0.351468299999965,"north":51.6723432,"east":0.14827100000002247}},"icon":"https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png","id":"b1a8b96daab5065cf4a08f953e577c34cdf769c0","name":"London","photos":[{"height":800,"html_attributions":["Edu Sousa"],"width":1200},{"height":1065,"html_attributions":["Manuel Ligabue"],"width":1600},{"height":1365,"html_attributions":["David Sun"],"width":2048},{"height":2136,"html_attributions":["Nuno Martins"],"width":3216},{"height":3000,"html_attributions":["Roberto Gerosa"],"width":4000},{"height":3024,"html_attributions":["ALLWYN D'SILVA"],"width":4032},{"height":1080,"html_attributions":["Cristina Cunsolo"],"width":1920},{"height":1362,"html_attributions":["Dendy Legends"],"width":2048},{"height":1440,"html_attributions":["Destiny Symonee"],"width":2560},{"height":1452,"html_attributions":["Leslie"],"width":5248}],"place_id":"ChIJdd4hrwug2EcRmSrV3Vo6llI","reference":"CmRbAAAAw49v9euZCWzrvjJ9b8STdg4qK48YueqQIOMerhQ43OP-NynPqFygwZnFzb-jcKkRKJog7z2IeUubF468akLhMj7pIZSoOWFXGjKC0WgkubgTIRlySRkBM47V9RMcX5YoEhB3qYHCQ3roB1G_gHnh_i8MGhSbxmofinNGCLquqddTEQ3DjsKOcg","scope":"GOOGLE","types":["locality","political"],"url":"https://maps.google.com/?q=London,+UK&ftid=0x47d8a00baf21de75:0x52963a5addd52a99","utc_offset":60,"vicinity":"London","html_attributions":[]}';
Here I attempt to convert it to an object:
var obj = JSON.parse(jsonString);
console.log(obj);
However when run I get an error:
Uncaught SyntaxError: Unexpected token l in JSON at position 492
I checked position 492, this is at the point where there is an '=' symbol.
Looking at it now, I believe this is the first occurence of an "=" symbol in this JSON string.
Why is this = symbol causing this error, and how can I prevent it?
Thanks!
You don't have to parse the JSON. JSON is a JavaScript Object Notation, so you can get rid of the strings and it will declare a JavaScript object for you to use.
You can use https://jsonlint.com to validate your JSON
Edit
Your JSON is incorrect. Near "adr_address": "<span class=" there is an error in your JSON. You should solve that first.
Related
Unable to correctly parse JSON object to a JavaScript Object
I have the following Json data that I am trying to transform to a Javascript object. Initially I tried using JSON.parse but it was saying an error so I figured the Json object was incorrectly configured. I did the following to resolve the issue. The JSON is given in the following form: {}{}{}... But I wanted to change it to the following format: [{},{},{}...] So I did the following var news = fs.readFileSync("data.json", "utf8") //Stringified data var newsdata = JSON.stringify(news) // add comma in between data = newsdata.replace('}{', '},{') // The resulting data doesn't have a comma between individual objects parsedNews = JSON.parse(data) The str.replace() command isn't changing it to a desired format. How should I resolve the issue?
Convert a Laravel Collection/Array to a Javascript Array
I would like to assign an array from Laravel to a JavaScript array. I have gotten the array from my AppServiceProvider and json_decoded it like: View::composer('*', function($view) { $users = Users::all(); $view->with(compact(users ); } I then access my $usersArray from my javascript file like: var dataSet = JSON.parse({!!$users !!}); I am however getting the following error; jQuery.Deferred exception: Unexpected token o in JSON at position 1 SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>)
Since you're encoding it in the server side, you need to decode it in the client side like: $chequesArray = Users::all()->toJson(); var dataSet = JSON.parse({!!json_encode($chequesArray)!!}); Or also Using "base64_encode" to conserve the json format like: $chequesArray = base64_encode(Users::all()->toJson()); var dataSet = JSON.parse(atob('{{$chequesArray}}'); The main difference comes from the use of {{ }} vs {!! !!}, the first one escapes the special chars so it will turn the quotes "" to " then the JS will be unable to parse the string (that why we can use `base64_encode``to conserve the format), the second one will conserve the format and allow the quotes what gives the JS part the ability to parse it simply.
var dataSet = #php $chequesArray #endphp;
How can I save & extract a json object as a string inside json from PHP to Javascript?
I'm trying to save a string which is encoded as json into another json string. In particular, I have to be able to handle empty objects: "{}". PHP: $sVal = "{}"; $jsonString = "{\"Var2\":\"My first var\", \"Var2\":\"My second var\", \"MyBlankObject\":\"{}\"}" ... Javascript: var oMyJSON = JSON.parse('< ?= $jsonString;? >'); I get a JSON parse error saying an unexpected { was found. I can see the code in Chrome's debugger. The brackets are simply removed and in the client side (javascript ) code, the object is replaced with the word null. That's not valid JSON. ,"Properties":null, This causes javascript to crash. If I try to json_encode it on the server side (PHP) I get double quotes on each side of the brackets. ,"Properties":""{}"", I get the same thing if I just add the double quotes: ""{}"" Of course, this causes javascript to crash too. Once in the client and I have the JSON object intact, I need to be able to extract the 'string' held in the property: MyBlankObject and then decode that JSON into a seperate JSON object. Everything I've tried fails. How can I accomplish this?
You can define the object using PHP notation, and let json_encode encode it for you. $phpArray = [ 'Var2' => 'My first var', 'Var2' => 'My second var', 'MyBlankObject' => new \stdClass ]; And then in the JavaScript: var oMyJSON = JSON.parse('<?= json_encode($phpArray); ?>');
JSON data being received in an incomplete format in php?
I'm building a super simple website application that calls an API to retrieve backlink data for any website inputted into said application by the user. The data the API sends includes strings (e.g. http://www.domain.com/?feed=rss) and numbers and is in JSON format. I parse the response as follows: mozResponse = JSON.parse(response); I then iterate through this data, pushing only the data I want into 2 new arrays (arry, arry1), declared as follows: arry = []; arry1 = []; Pushing as follows: arry.push({id:i, url:mozResponse[i].uu, pa:Math.round(mozResponse[i].upa), da:Math.round(mozResponse[i].pda), anchor:mozResponse[i].lt}); I then Stringify these two arrays as follows: var cautionArrayString = JSON.stringify(arry); var dangerArrayString = JSON.stringify(arry1); I'm using a JavaScript XMLHTTPRequest to POST this data to a php file as follows: var queryString = "email=" + Email + "&caution=" + cautionArrayString + "&danger=" + dangerArrayString; xhr1.onreadystatechange=Response1; xhr1.open("post","http://example.com/emails.php",true); xhr1.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr1.send(queryString); The php file then reads: $caution = $_POST['caution']; $danger = $_POST['danger']; I'm aware at this point I should decode the JSON again upon originally doing so I ended up with a broken array. Here's what the console.log reads AFTER posting the data to the php file, with the php file using: echo($_POST['caution']); echo ($_POST['danger']); Console.log shows: [{"id":3,"url":"example.ca/","pa":26,"da":12,"anchor”:”Example”}, {"id":4,"url":"example.ca/","pa":26,"da":12,"anchor":"thank you gifts"}, {"id":5,"url":"example.ca/","pa":26,"da":12,"anchor":"flowers"}, {"id":6,"url":"example.ca/","pa":26,"da":12,"anchor":"thank you"}, {"id":7,"url":"example.ca/","pa":26,"da":12,"anchor":"Arrive in Style"}, {"id":8,"url":"example.ca/","pa":26,"da":12,"anchor":"dignity"}, {"id":9,"url":"example.ca/","pa":26,"da":12,"anchor":"Beautiful in Blue"}, {"id":10,"url":"example.ca/","pa":26,"da":12,"anchor":"Blooming Garden Basket"}, {"id":11,"url":"example.ca/","pa":26,"da":12,"anchor":"Country Basket Blooms"}, {"id":12,"url":"example.ca/","pa":26,"da":12,"anchor":"Heart’s Delight"}, {"id":13,"url":"example.ca/","pa":26,"da":12,"anchor":"Make a Wish"}, {"id":14,"url":"example.ca/","pa":26,"da":12,"anchor":"Moondance"}, {"id":15,"url":"example.ca/","pa":26,"da":12,"anchor":"Queen’s Court"}, {"id":16,"url":"example.ca/","pa":26,"da":12,"anchor":"Sweet as Sugar"}, {"id":17,"url":"example.ca/","pa":26,"da":12,"anchor":"flower colors"}, {"id":18,"url":"example.ca/","pa":26,"da":12,"anchor":"Always Yours"}, {"id":19,"url":"example.ca/","pa":26,"da":12,"anchor":"Sunrise, Sunset"}, {"id":20,"url":"example.ca/","pa":26,"da":12,"anchor":"Uniquely Chic"}, {"id":21,"url":"example.com/best/index.php?page=1998","pa":25,"da":31,"anchor":"example.ca/"}, {"id":22,"url":"example.com/best/index.php?page=1994","pa":25,"da":31,"anchor":"example.ca/"}, {"id":23,"url":"example.ca/","pa":25,"da":16,"anchor”:”example”}, {"id":28,"url":"example.ca/article/156-best-cms-for-small-business","pa":22,"da":39,"anchor":"example.ca/"}, {"id":30,"url":"example.ca/blog.html","pa":21,"da":15,"anchor":"example.ca/"}, {"id":31,"url":"example.ca/beyond-the-flowers-choosing-a-vase/","pa":20,"da":12,"anchor”:”Example”}, {"id":32,"url":"example.ca/beyond-the-flowers-choosing-a-vase/","pa":20,"da":12,"anchor":"Arrive in Style"}, {"id":33,"url":"example.ca/beyond-the-flowers-choosing-a-vase/","pa":20,"da":12,"anchor":"Beautiful in Blue"}, {"id":34,"url":"example.ca/beyond-the-flowers-choosing-a-vase/","pa":20,"da":12,"anchor":"Blooming Garden Basket"}, {"id":35,"url":"example.ca/beyond-the-flowers-choosing-a-vase/","pa":20,"da":12,"anchor":"Country Basket Blooms"}, {"id":36,"url":"example.ca/beyond-the-flowers-choosing-a-vase/","pa":20,"da":12,"anchor":"Heart’s Delight"}, {"id":37,"url":"example.ca/beyond-the-flowers-choosing-a-vase/","pa":20,"da":12,"anchor":"Make a Wish"}, {"id":38,"url":"example.ca/gifts.html","pa":19,"da":11,"anchor”:”example- <span class=\"catlist\"> Flowers</span>"}, {"id":39,"url":"example.ca/category/flowers/","pa":19,"da":16,"anchor”:”Example”}, {"id":40,"url":"example.ca/category/floral-fauna/","pa":19,"da":16,"anchor”:”Example”}, {"id":41,"url":"nunavut.findstuffhere.ca/nunavut/?feed=rss2[] Where you can see AT THE END that the 1st array is incomplete and the 2nd is empty (as it should be!). So my question here is, what's causing this and how can I fix it? Things to Note I use 3 URL's as inputs to test. The data is complete with 1 URL, but 2 others (the example above included) return this incomplete JSON, seemingly because of a query string being a part of a URL returned from the API? I console.log(mozResponse) and the output is as expected I console.log(arry) and console.log(arry1) AFTER iterating through mozResponse and pushing data from mozResponse to arry/arry1 and the output is a complete array I console.log(arry) and console.log(arry1) AFTER applying JSON.stringify but BEFORE posting to php and the output is complete Things I've explored I originally thought this was the result of one of the URL's that the API returns including a query string (e.g. ?feed=rss2 where it breaks) however prior to this break point there are query strings being handled fine Doesn't seem to be a JSON error as I used json_last_error(); and it returned 0. Also doesn't seem to be a a JSON/POST char limit thing because it returns broken JSON when I input a different URL (the output from the $_POST for this URL also breaks following a query string, not sure if this is coincidence) Suhosin isn't present Created a phpinfo page to check max_vars but the limit is large Any help is greatly appreciated! *different quotes are from copy/pasting!
You probably just need to encode your values for use in a query string: var cautionArrayString = encodeURIComponent(JSON.stringify(arry)); var dangerArrayString = encodeURIComponent(JSON.stringify(arry1)); var queryString = "email=" + encodeURIComponent(Email) + "&caution=" + cautionArrayString + "&danger=" + dangerArrayString; Converting it to json does not automatically encode it correctly for use in a url so characters in your values could break the query string. Assuming the different quotes are caused by copy-pasting...
Passing (and parsing!) JSON objects through MVC4
I'm confused as to how I should be using JSON objects within MVC and how they should passed from Controller, to View, to Jscript. I'm also not sure if I'm correctly parsing the JSON objects at the right points... My controller is returning a PartialView with a json object ("Variables" is a list of data e.g. Id=2012, Name=BillyJoel, Value="£2,000"): public ActionResult JavascriptConstants() { var variables = Service.Obtain<VariableService>().All().ToList(); var json = new JavaScriptSerializer().Serialize(variables); return PartialView("JavascriptConstants", json); } My View then makes this data available to my scripts by creating this variable: #model string ... var mvcListOfVariablesInDB = '#Html.Raw(Json.Encode(Model))'; My Jscript file then accesses the data and attempts to pull out the information and key value pairs, but seems to be interpreting the JSON as a string: var variableList = $.parseJSON(mvcListOfVariablesInDB); for (var variable in variableList) { alert(variableList[variable]); } This just returns alerts of ", [, {, etc. as each character of the string is displayed. How do I access the key values of the JSON object? I've tried changing my JS to use: var variableList = $.parseJSON(mvcListOfVariablesInDB); But this just gives me an Uncaught SyntaxError: Unexpected token I error in my browser (I'm assuming when it hits the "I" of "Id). Any help much appreciated, thanks.
I found the issue: The issue was the use of JavaScriptSerializer().Serialize(foo) as this was creating a JSON object that contained newlines and tabs instead of replacing them with \n and \t. $.parseJSON() cannot handle newlines and so throws up unexpected token error. This was corrected by importing the JSON.NET package and using : var json = JsonConvert.SerializeObject(variables); This passed a JSON object with newlines and tabs replaced with \n's and \t's. Which can then be made accessible to the View using: #model string ... var mvcListOfVariablesInDB = '#Html.Raw(Json.Encode(Model))'; and finally in the script using: var variableList = $.parseJSON(mvcListOfVariablesInDB) Hope this helps someone else one day...