parsing multidimensional javascript json array with php - javascript

I have the following multidimensional javascript array:
My js array
and I want to parse it and return some values from it (name and url)
but when cleaning it up a bit $jsonData = str_replace('var stations = ','' ,$jsonDataUrl); and trying to parse it as json with json_decode($jsongoeshere), the parser returned error 4 even if this URL had told me
that The JSON input is valid in JavaScript.
So now I am a bit lost on how to parse it.

quoted object property name expected is your error.
Your JSON string is not valid, object property names must be quoted.
This
{
"aland": [
{
name: "Ålands Radio",
logo: "stations/images-europe/aland/Ålands Radio.png",
url: "http://194.110.182.131:8000/stream.ogg"
},
...
Should be
{
"aland": [
{
"name": "Ålands Radio",
"logo": "stations/images-europe/aland/Ålands Radio.png",
"url": "http://194.110.182.131:8000/stream.ogg"
},
...
These JSON validators give you the correct error.
https://jsonlint.com/ & https://jsonformatter.curiousconcept.com/
Also, what #JJAulde said is true.
You have a semicolon at the end of your JSON string that will cause the parse to fail. You need to rtrim or str_replace it like you did with var stations =

Related

parse “application/x-www-form-urlencoded” response with javascript

How do you parse a x-www-form-urlencoded string with JavaScript?
I tried to parse to JSON and able to iterate the keys using Object.Keys()
my responseText = {
"response": {
"header": {
"error_code": 0
},
"body": {
"foo": "foobar",
"date": "2018-04-27"
}
}
}
Url encoded forms have the structure key=value&key2=value2&.......
The keys and values are encoded, for more info on url encoding: https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4
In case any value is an object with more keys and values inside it, the form will contain each of the keys inside said object as a description of their path relative to the root, using [].
Your example would look like:
response[header][error_code]=0&response[body][foo]=foobar&response[body][date]=2018-04-27
I think with this info you can probably figure it out, just keep in mind that the text is encoded, unlike in my example.

Parse JSON string as an array using JavaScript

May seem silly for most of you but I need to parse a JSON string as an array using JavaScript.I'm completely new to JSON and JavaScript and trying to make sense since last two days.
I need to read this JSON as an array and parse it using Javascript. In this example the JSON returned is single element, however in specific cases it returns multiple results(array)
[
{
"CauseAndEffect_Status": "InProgress",
"CurrentPhase": "Planning",
"cityCountry": "Walker French Southern Territories",
"location": "bangalore",
"siteAddress": "Sharon Street Canda Avenue",
"siteName": "DAISU",
"status": "95%",
"zipCode": 12940
}
]
Although the above JSON is an array object,I get the following error when I try to parse this JSON
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data of Jquery-2.1.4.min.js
If it comes from the server as a string, you can use
var myArray= JSON.parse(myJsonString);
and you you'll have an array of objects myArray which you can cicle with a simple for loop
Code For Parsing Json in Javascript . See the Js Fiddle below
var str ='{"CauseAndEffect_Status": "InProgress","CurrentPhase": "Planning", "cityCountry": "Walker French Southern Territories","location": "bangalore","siteAddress": "Sharon Street Canda Avenue","siteName": "DAISU","status": "95%","zipCode": 12940}';
var json = JSON.parse(str);
console.log(json);
$.each( json, function( ky, val ) {
console.log('ky => '+ky);//will output: name, firstname, societe
console.log('val => '+val);//will output: name1, fname1, soc1
});
CHECK THE BROWSER CONSOLE TO SEE RESULT

difference beetween JSON and javascript object [duplicate]

This question already has answers here:
What is the difference between JSON and Object Literal Notation?
(10 answers)
Closed 7 years ago.
i cant see the difference between:
self.todos = [{
"todo": {
"title": "title",
"content": "lorem"
}
}, {
"todo": {
"title": "title",
"content": "lorem"
}
}];
and
self.todos = [{
todo: {
title: "title",
content: "lorem"
}
}, {
todo: {
title: "title",
content: "lorem"
}
}];
both work in my code but only the first veryfies JSON (online JOSON veryfier). Is there a preference what to use.
thanks a lot
The strict difference between JSON and JavaScript literals is only how you use it.
JSON is a text format to represent data. JavaScript literals is a part of JavaScript code.
You can't use JSON in JavaScript code, because then it's by definition not JSON any more, it's JavaScript. You can take JSON and use as JavaScript code, however. You can also have JSON inside a string in JavaScript.
JSON syntax is a subset of JavaScript literals syntax, so you can take any JSON and use as JavaScript, but you can't take any JavaScript literal and use as JSON.
This is an example of JSON:
[{
"todo": {
"title": "title",
"content": "lorem"
}
}]
You can use that as JavaScript:
var arr = [{
"todo": {
"title": "title",
"content": "lorem"
}
}];
You can also have the JSON as a string and parse it to a JavaScript value:
var json = '[{ "todo": { "title": "title", "content": "lorem" } ]';
var arr = JSON.parse(json);
Note that parsing JSON does't use the JSON as JavaScript, it reads the JSON and creates JavaScript values that corresponds to it. (Before JSON parsing was available the eval function was used to parse JSON, and that would actually use the JSON as JavaScript. JSONP requests still use JSON as JavaScript, as it loads the data using a script tag.)
JavaScript is less strict and doesn't require delimiters for object property names that can be used as identifier. Also, you can use expressions when creating JavaScript literals:
var arr = [{
todo: {
title: document.title,
content: "lo" + "rem"
}
}];
If you take that JavaScript literal and try to use as JSON, the syntax is wrong.
If you're writing JSON, you must conform to the rules for JSON, which include the fact that the property names must be in double quotes. (And that strings must be in double, not single quotes, and there's no undefined or functions, and various other things...)
What you're writing clearly isn't JSON, however, it's JavaScript code; I can tell from the self.todos = part. So you can use no quotes, single quotes, or double quotes on the property names; it's up to you. There are some property names where you need quotes, for instance when the property name has a space:
var o = {
"I have a space": 42
};
The key distinction is that JavaScript source code is source code, and JSON is a textual notation for data exchange which is a simplified version of one small part of JavaScript source code. When you're dealing with JavaScript source code, you're not dealing with JSON, unless you're dealing with strings (e.g., a string containing JSON, which you might parse or send to a server or similar).

javascript (no jquery) - load a local json file

I have a local JSON file which I converted into a JS object by adding var data = ... in front of that:
var data = {
"people": [
{
"name": "Martin",
"surname": "Smith"
},
{
"name": "Jack",
"surname": "Smith"
}
]
}
I load it with: <script src="data.json" type="text/javascript"> and try to parse it with:
var h = JSON.parse(data);
I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
When you put var data = { in front of it, it stops being JSON and becomes JavaScript. (So you shouldn't give it a .json file extension and that will encourage servers to tell browsers that it is JSON and not JS).
In this case, it is a JavaScript program that assigns an object to a variable.
JSON.parse takes a string containing JSON and converts it into a JavaScript object (or array or other data type).
Don't parse it. It is already parsed by the JavaScript compiler.
Here MZN JSON.parse() you can see what JSON.parse() should be used for. It is used on a String that contains a JSON object, and this method would parse it into the format that your data variable is already in. Since your data variable is already in JSON format, your variable is ready to use and you do not need the JSON.parse() method.

Random " Being picked up by javascript

I am passing an array from php to javascript but it seems to be picking up a extra " at the start and finish of the array.
My array being sent from the PHP file
json_encode($CheckItems."|".$CheckUserItems."|".$CheckUserMessages."|".$CheckCommentsForproducts."|".$CheckComments);
My File reciving the array.
url: 'CheckServer.php',
success: function(data) {
var DataBaseCheck = (data)
DataBaseCheck = data.split("|");
console.info(DataBaseCheck);
Console.info prints ""0","1","2","3""
When checking if Database[0] matches with anther variable it fails due to the extra " when i console log each array i get "0,1,2,3"
How can i solve this i have tried
DataBaseCheck.replace('""','"')
DataBaseCheck.replace('"','')
Array1 = parseInt(DataBaseCheck[0])
I cannot think of any other way to remove them ??
The "extra double quotes" are there because you have a JSON encoded string. You are getting JSON from your PHP code, so in your JavaScript the first step should be to decode it:
function(data) {
data = JSON.parse(data);
data = data.split("|");
# data is now an array of strings, e.g. ["0", "1", "2", "3"]
}
Really though, if you are trying to pass an array of integers from your PHP code to your JavaScript code, rather than using your own delimiter you are better off just creating an array in PHP and JSON encoding that, then your JavaScript would just be JSON decoding and you would have the correct data.

Categories

Resources