AJAX / javascript: parsing JSON that contains an array - javascript

I'm trying to parse a JSON message that my page gets through an AJAX response however, it keeps throwing the following error and I have no clue why:
"SyntaxError: JSON.parse: expected ',' or ']' after array element of the JSON data"
Here is what my page's javascript looks like:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var Response = JSON.parse(xhttp.responseText);
}
}
And here is what the JSON the server returns looks like:
{
"Error": "",
"ClientInfo": [{
"ID": 1,
"Name": "Bill"
}, {
"ID": 2,
"Name": "Sally"
}]
}
Any idea what I'm doing wrong? JSON validators say it's valid JSON....

UPDATE
It's that Error: key that's making the parser vomit it back out. See the demo.
Updated demo to include the JSON with Error: to compare results. Unfortunately, I had to comment out the console logged the error JSON because the debugger picked up on the Script error immediately. Fortunately, the demo still functions so you can ignore the initial error after loading.
TEST 1
Try the info button first. [Result: Sally]
Next click the error0 button. [Result: Sally]
Then try the error1 button. [Result: undefined]
So it seems to parse if you:
Remove the Error:""
OR
Place the Error: "" inside the array.
TEST 2
Copy the info JSON then validate it. JSONLint
When you use JSONLint, you must strip it:
{
"ClientInfo": [
{
"ID": 1,
"Name": "Bill"
},
{
"ID": 2,
"Name": "Sally"
}
]
}
Now copy the error JSON and validate it.
{
"Error": "",
"ClientInfo": [{
"ID": 1,
"Name": "Bill"
}, {
"ID": 2,
"Name": "Sally"
}]
}
Both of them should be valid, yet the debugger and the parser reject the error JSON.
Snippet
// Prepare JSON
var info =
'{"ClientInfo": [' +
'{"ID": 1, "Name": "Bill"},' +
'{"ID": 2, "Name": "Sally"} ]}';
var error0 =
'{"ClientInfo": [' +
'{"ID": 1, "Name": "Bill"},' +
'{"ID": 2, "Name": "Sally"},' +
'{"Error": ""} ]}';
var error1 =
'{"Error": ""},' +
'{"ClientInfo": [' +
'{"ID": 1, "Name": "Bill"},' +
'{"ID": 2, "Name": "Sally"} ]}';
// Create a function that parses JSON Object
function JSONObj(json) {
var jsonObj = JSON.parse(json);
return jsonObj;
}
// A function that logs results one at a time so we can compare results
function processLog(result) {
console.log('Result: ' + result);
}
/* Test info and errors */
var lastClient = JSONObj(info).ClientInfo[1].Name;
var errorA = JSONObj(error0).ClientInfo[1].Name;
var errorB = JSONObj(error1).ClientInfo[1].Name;
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<ol>
<li>Remove this: <pre><code>"Error": "",</code></pre>
</li>
<li>Separate into segments (see script)</li>
<li>Wrap each segment with single quotes `'`</li>
<li>Add a `+` after each segment</li>
</ol>
<button onclick="processLog(lastClient);">info</button>
<button onclick="processLog(errorA);">error0</button>
<button onclick="processLog(errorB);">error1</button>

Json parser takes in json string and parses it. You already have a json object

Related

Working with nested JSON object gives me console error

Working with a JSON nested object and I get an error when running in the javascript console "JSON3.html:11 Uncaught SyntaxError: Invalid or unexpected token"
I've verified the JSON via https://jsonformatter.org/json-viewer and that looks ok. The output is only the text in my h2 tag. What am I missing?
Here's the code.
<!DOCTYPE html>
<html>
<body>
<h2>Testing JSON .</h2>
<p id="demo"></p>
<script>
var myJSON = '{
"LevelOne": {
"LevelTwo": {
"location": {
"campus": "SouthWest",
"building": "Biggest",
"floor": "1st",
"room": "101"
},
"quantity": "1",
"section": "ABC",
"task": "abc123456zyx"
}
}
}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myJSON.LevelOne.LevelTwo.location;
</script>
</body>
</html>
String concatenation
String that are surrounding using " and ' cannot extend over multiple lines, so have to separate each line and then concatenate them. Example:
var myJSON = '{' +
'"LevelOne": {' +
'"LevelTwo": {' +
'"location": {' +
'"campus": "SouthWest",' +
'"building": "Biggest",' +
'"floor": "1st",' +
'"room": "101"' +
'},' +
'"quantity": "1",' +
'"section": "ABC",' +
'"task": "abc123456zyx"' +
'}' +
'}' +
'}';
console.log(myJSON);
Template Literals
In ES6, template literals were added, that allow to have strings span through multiple lines, provided you use ` instead of " or '. Example:
var myJSON = `{
"LevelOne": {
"LevelTwo": {
"location": {
"campus": "SouthWest",
"building": "Biggest",
"floor": "1st",
"room": "101"
},
"quantity": "1",
"section": "ABC",
"task": "abc123456zyx"
}
}
}`;
console.log(myJSON);
Removes the new lines from the JSON
A simple way to make the JSON 1 line tall is to do JSON.stringify(json) at the browser's console.
Use a normal JSON
You can just use the normal object notation of the JSON instead of the JSON and then if you want to you can convert it back to a string using JSON.stringify. Example:
var myJSON = {
"LevelOne": {
"LevelTwo": {
"location": {
"campus": "SouthWest",
"building": "Biggest",
"floor": "1st",
"room": "101"
},
"quantity": "1",
"section": "ABC",
"task": "abc123456zyx"
}
}
};
console.log(JSON.stringify(myJSON));
console.log(myJSON);
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).Including parsing JSON so you can access data within it, and creating JSON
Instead of using JSON data as a string you can directly add the JSON
data or use the double quote.if you are storing the JSON object of object in a variable using single quote, You just > write add the JSON data string in a single line or else use the double quote.
Example
<!DOCTYPE html>
<html>
<body>
<h2>Testing JSON .</h2>
<p id="demo"></p>
<script>
var myJSON = '{"LevelOne": {"LevelTwo": {"location": { "campus": "SouthWest","building": "Biggest","floor": "1st", "room": "101"},"quantity": "1","section": "ABC","task": "abc123456zyx"}}}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.LevelOne.LevelTwo.location;
</script>
</body>
</html>
You can get the result.!
Another Solution
myJSON.LevelOne.LevelTwo.location is OBJECT
var myJSON =
{ LevelOne:
{ LevelTwo:
{ location:
{ campus: "SouthWest", building: "Biggest", floor: "1st", room: "101"}
, quantity: "1"
, section: "ABC"
, task: "abc123456zyx"
}
}
}
console.log ( myJSON.LevelOne.LevelTwo.location )
// ===> OBJECT

Javascript:Json Array Data is undefined

I have json array data like this:
var arr= [
{
"id": 1,
"organizationName": "psda",
"Number": "12345"
},
{
"id": 2,
"organizationNameEN": "psda",
"Number": "123456"
}
]
AND after getting this data from json file i will use
var arr1=JSON.stringify(arr)
and then use
var arr2=JSON.parse(arr1)
var i=0;
while(i>=0){
var Data = $scope.documentData = {
"id":arr2[i]["id"],
"organizationNameGE":arr2[i]["organizationName"],
"Number":rawData[i]["Number"]
};
i++}
methods after that i try to get id arr2[i]["id"] and it seems to be undefined ,it throws exception like this Form failure:
Cannot read property 'id' of undefined
What should i change to make my code work?
Method 1
actually...you can't access the arr2[i].["id"] from while loop.
so create a global variable and then use it with this keyword
Method 2
if you are using angular framework.Try using with foreach loop.
var arr= [
{
"id": 1,
"organizationName": "psda",
"Number": "12345"
},
{
"id": 2,
"organizationNameEN": "psda",
"Number": "123456"
}
];
var arr1=JSON.stringify(arr);
var arr2=JSON.parse(arr1);
arr2.forEach(element =>{
alert(element.id);
});

Push Json filtered key values to nested ul with Javascript

I need help pushing the values from a filtered json, I need this generate a nested ul list, I can not modify the json format at this point, I you check the console.log you will see the values to create the list, at this point I can't figure how to complete the 'for loop' to render the html markup needed, any help will be appreciated, this is the jsfiddle http://jsfiddle.net/43jh9hzz/, and if you check the console log you will see the values.
This is the Js:
var json='';
var property_set = new Set();
function iterate(obj, stack) {
json="<ul>";
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property], stack + '.' + property);
}
else {
// console.log(property);
property_set.add(property);
json+="<li>";
if(typeof obj[property] !== "number") {
json+="<li>"+obj[property]+"</li>";
console.log(obj[property]);
}
}
} json += "</li>";
}
}
var listEl = document.getElementById('output');
iterate(jsonObj)
And this is the json format:
var jsonObj =
{
"level_1": [
{
"level_1_name": "CiscoSingaporeEBC",
"level_2": [
{
"level_2_name": "Khoo Tech Puat",
"level_2_id": 2222,
"level_3": [
{
"name": "Boon Leong Ong",
"id": 6919
},
{
"name": "Kiat Ho",
"id": 6917
},
{
"name": "Overall Experience",
"id": 6918
}
]
}
]
},
{
"level_1_name": "CiscoLondonEBC",
"level_2": [
{
"level_2_name": "Bernard Mathews Ltd.",
"level_2_id": 2367,
"level_3": [
{
"name": "Barry Pascolutti",
"id": 7193
},
{
"name": "Kathrine Eilersten",
"id": 7194
},
{
"name": "Martin Rowley",
"id": 7189
}
]
},
{
"level_2_name": "FNHW Day 1",
"level_2_id": 5678,
"level_3": [
{
"name": "Jurgen Gosch",
"id": 7834
},
{
"name": "Overall Experience",
"id": 7835
}
]
},
{
"level_2_name": "Groupe Steria Day 1",
"level_2_id": 2789,
"level_3": [
{
"name": "Adam Philpott",
"id": 7919
},
{
"name": "Pranav Kumar",
"id": 7921
},
{
"name": "Steve Simlo",
"id": 7928
}
]
}
]
}
]
};
enter code here
I'm not sure if I am interpretting your request correctly, but I think this is what you want: http://jsfiddle.net/mooreinteractive/43jh9hzz/1/
Basically, you are calling the iterate function to run, but then that's it. The function actually needs to also return the value it generates.
I've added to the end of the function, after the for loop completes:
return json;
Do now the function returns the value it generated, but there are some other issues too. When you recursively call the iterate function again inside the iterate function, you actually want to add what it returns to the current json string housing all of your returned value.
So on that line I changed it from:
iterate(obj[property], stack + '.' + property);
to
json += iterate(obj[property], stack + '.' + property);
Now that other value will come back as well inside the main list you were creating in the first run of the function. Ok so that's pretty close, but one more small thing. I think when you added additional surrounding LI, you actually wanted to do an UL. I changed those to ULs and now I think the result is like a UL/LI list representing the text parts of the JSON object.
Again, that may not be exactly what you were after, but I think the main take away is using the function to return the value, not just generate it, then do nothing with it.

How to parse a JSON array string in JavaScript?

I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']

how to convert the string into json object?

I use the ajax which sends back a string..
I want to convert the responsetext into a json object to process.
I tried eval and also , but doesn't works...
Wht to do?
My code is
function handleResponse() {
if (httpa.readyState == 4) {
var response = httpa.responseText;
if (response != 'empty') {
alert(response);
var foo = eval('(' + strJSON + ')');
alert(foo);
}
}
}
// response alerts
[{
"id": "1",
"name": "Pepsodent 100g",
"selling_price": "28.75"
}, {
"id": "2",
"name": "Pepsodent 40g",
"selling_price": "18.90"
}, {
"id": "3",
"name": "Pepsodent brush",
"selling_price": "19.50"
}]
Using https://github.com/douglascrockford/JSON-js/blob/master/json2.js
you can do
JSON.parse(response, reviver)
http://www.json.org/js.html
Change strJSON to response.

Categories