JSON.parse: expected ',' or '}' after property value in object - javascript

I keep getting this error message when I load my human.json file via AJAX.
The whole error message reads
JSON.parse: expected ',' or '}' after property value
in object at line 2 column 22 of the JSON data.
I looked online for it, and there have been people who had similar error messages, however, they are not calling via AJAX.
In addition to that, they are not nesting arrays within objects within objects. I think that is the reason why I am getting this error message. Are you not allowed to nest that many properties into each other?
Here's my AJAX code:
var request = new XMLHttpRequest();
request.open('GET','human.json');
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var obj = JSON.parse(request.responseText);
console.log(obj);
}
}
request.send();
and my human.json file:
{
"sex":{
"male":{"fname":["Michael", "Tom"]},
"female"
},
"age":[16, 80],
"job":[]
}

Your object isn't valid JSON. Specifically at the part:
,"female"}
A JSON property must have a value. Maybe that should that be:
,"female":{}}
or:
,"female":null}

Your JSON file has a syntax error. The following is reformatted to highlight the error:
{
"sex":{
"male":{"fname":["Michael","Tom"]},
"female" <----------------- SYNTAX ERROR
},
"age":[16,80],
"job":[]
}
In JSON, objects have the syntax:
{"name" : "value"}
The syntax {"foo"} is invalid according to JSON spec. Therefore you need to provide some value for the female attribute:
{
"sex":{
"male":{"fname":["Michael","Tom"]},
"female":{}
},
"age":[16,80],
"job":[]
}

Your JSON is indeed invalid.
{
"sex": {
"male":{
"fname": ["Michael","Tom"]
},
"female" ## Here is the problem
},
"age": [16,80],
"job": []
}
Perhaps change that line to:
"female": {}
It all depends on what you're wanting to do

your "female" is error, need a key or value
you can change the json file to
{
"sex":{"male":{"fname":["Michael","Tom"]} ,"female":null},
"age":[16,80],
"job":[]
}

JSON file used by you is invalid json. JSON is a collection of name/value pair. Each key in the JSON should contain value. In your case, key "Female" doesn't have any value. Below shown is the valid JSON format.
{
"sex": {
"male": {
"fname": ["Michael", "Tom"]
},
"female": "XXX"
},
"age": [16, 80],
"job": []
}

Related

Why am I getting an error that my conditions don't match the schema?

I have this query that works:
{
"TableName": "myTable",
"IndexName": "gsi1",
"Limit": 12,
"KeyConditionExpression": "#pk = :pk",
"ExpressionAttributeValues": {
":pk": "TOS"
},
"ExpressionAttributeNames": {
"#pk": "gsi1_pk"
}
}
I attempted to convert it into one using KeyConditions instead of an expression because that makes other things easier. So I changed it to this:
{
"TableName": "myTable",
"IndexName": "gsi1",
"Limit": 12,
"KeyConditions": {
"gsi1_pk": {
"ComparisonOperator": "EQ",
"AttributeValueList": [
{
"S": "TOS"
}
]
}
}
}
I have the GSI configured on my table:
But when I make the request I'm getting this error:
ValidationException: One or more parameter values were invalid: Condition parameter type does not match schema type
I don't understand why I'm getting this error.
My Partition key for this GSI is a string
The only attribute I'm querying against is a string
The name gsi1_pk matches the value I'm querying
Did I miss something in converting this query? I don't understand what I should change to resolve the error because it looks accurate to me.
From this aws doc
This is a legacy parameter. Use KeyConditionExpression instead.
'KeyConditions' >= 'KeyConditionExpression'
Changing your key var in your query should fix this.

Create and Read JSON file

I created a JSON file as follows
{
"fooditems" : [
{
"name": "pizza",
"type": "fastfood",
"price": 10
},
{
"name": "apple",
"type": "fruit",
"price": 1
}
]
}
created a JS file to read the JSON file
const data = require("./data.json");
data1 = JSON.parse(data);
data1.foodData.forEach( foodItem => console.log(foodItem));
When I run the JS, I get error for the json file
Syntax error: Unexpected token o in json at position 1
at JSON.parse
You don't need to parse data since it's already and object. The following should work.
const data = require("./data.json");
data.fooditems.forEach( foodItem => console.log(foodItem));
Note foodData was change to fooditems based on the contents of the data.json file.
Your initial data JSON contains "fooditems", but in the JS file you are trying to process the "foodData". Change the "foodData" to "fooditems" and it should work.
I think that you are trying to access invalid object key in your JS file on the last line.
Instead of
data1.foodData
put
data1.fooditems

Getting data from Json string into javascript (jQuery)

I have a asp.net webservice, which is pulling some data from my database, and outputting this JSON string:
{
"NumberOfCustomers": 15,
"Customer": [
{
"CusID": "1",
"FirstName": "Ina",
"LastName": "Williamson"
},
{
"CusID": "2",
"FirstName": "Hyacinth",
"LastName": "Brady"
},
{
"CusID": "3",
"FirstName": "Coby",
"LastName": "Shannon"
}
]
}
I then try to use jQuery to display each of the customers, but i can't get it working. The purpose for this, is to use the data as a suggestion to a search field, that updates for each character written.
function FinalTest() {
$.ajax({
type: "POST",
url: "http://localhost:12724/VetWebservice.asmx/GetCustomer",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
glb = data; //variable for inspecting in Chrome
$("#testdiv3").html(data.d.NumberOfCustomers);
$.each(data.d.Customer, function () {
$("#testdiv3").append(this.CusID + ", ");
});
}
});
};
Giving me this error:
TypeError: a is undefined
jquery.min.js (linje 2)
It has something to do with the pointing to specific parts of the JSON array. But i can't figure out why it isnt working.
The "d" of the data.d path, is because asp.net webservice for some unknown reason wraps it in a d key property.
data.d.NumberOfCustomers
Its also possible to change the JSON string that i create from my webservice, if that would help solving it somehow. But my JSON syntax validates on jsonlint.com
Any help or suggestions will be highly appreciated.
EDIT: added glb object for inspecting + the result of it from Chrome
Inspecting the "glb" gives this result:
Object {d: "{"NumberOfCustomers":15, "Customer":[{"CusID":"1",…D":"15","FirstName":"Adele","LastName":"Woods"}]}"}
Which looks like what i expect; wrapped in the "d" property cause of the asp.net webservice.
When running my jquery snippet in Chrome, im also getting this error:
Uncaught TypeError: Cannot read property 'length' of undefined jquery.min.js:2
n.extend.each jquery.min.js:2
FinalTest.$.ajax.success Customers.aspx:226
j jquery.min.js:2
k.fireWith jquery.min.js:2
x jquery.min.js:4
b jquery.min.js:4
You should be using
data.NumberOfCustomers
instead of
data.d.NumberOfCustomers
and
data.Customer
instead of
data.d.Customer
.
i've tried the following code in the chrome console and it worked:
data = {
"NumberOfCustomers": 15,
"Customer": [
{
"CusID": "1",
"FirstName": "Ina",
"LastName": "Williamson"
},
{
"CusID": "2",
"FirstName": "Hyacinth",
"LastName": "Brady"
},
{
"CusID": "3",
"FirstName": "Coby",
"LastName": "Shannon"
}
]}
$.each(data.Customer,function() { alert(this.CusID); });
I remember asp.net webmethod put the result in property d but perhaps its structure a bit different then what you expect.
I would suggest to add an assignment to global var the value returned from service and investigate it using the console.
in the ajax success add line at the head of the function as follows:
glb = data; //glb will be a global scope var which you can investigate on console upon end of execution.
than on chrome console just type glb and press enter. then you would be able to investigate the object and try the each function without doing the ajax call.

Update JSON with jquery error

I'm trying to update a JSON file with the value of a textarea using jquery push. I'm receiving the following error: " JavaScript runtime error: Unable to get property 'push' of undefined or null reference"
My jquery:
function submittedMsg(ctx) {
var id = $('.msg-input form').attr('id');
var newMsg = $('.msg-input textarea').val();
var url = "/ajax.aspx?vtl=ajax-conversation-json&cv=" + id;
$.getJSON(url, function (messageString, message) {
var message = [];
message.push({
msgcontent: newMsg,
sendname: sendRname,
mbrhref: mbrUrl,
datetime: ""
});
});
}
My JSON:
{
"messageString" :
[
{ "subject": "hello",
"msgstring": "5",
"unread": "1",
"datetime": "Oct 1 2013 9:59PM",
"orderid": "17",
"recipient": [
{
"mbrname": "Jane Doe",
"mbrhref": "/profile.aspx?mem=1227"
},
{
"mbrname": "John Smith",
"mbrhref": "/profile.aspx?mem=1337"
}
],
"message": [
{
"datetime":"2013-10-01T21:59:33.063",
"sendname":"Jane Doe",
"mbrhref":"/profile.aspx?mem=1227",
"msgcontent": "<p>Hi. I would like to talk with you about Dwarf Beryl Beauty</p>"
},
{
"datetime":"2013-11-26T16:29:17.037",
"sendname":"John Smith",
"mbrhref":"/profile.aspx?mem=1337",
"msgcontent": "Tough luck."
}
]
}
]
}
I don't necessarily need to use push to update the JSON file if there is a better way, I'm open to suggestions. I've verified my URL path is correct. Am I just missing something obvious? I'm new to JSON and only have passable jquery skills. Help!
Thanks in advance for any direction.
Try to use:
data.message.push
instead of:
data.messageString.message.push
Ah I see the issue, you have a local var and parameter of the same name message:
$.getJSON(url, function (messageString, message) { //here is param message
var message = []; //here is a local var parameter
message.push({ //this is probably referencing the parameter which is not an array or object that supports .push
Instead:
$.getJSON(url, function (data) { //I renamed the param to be more consistent with documentation, although it doesn't really matter, just will generate confusion
data.messageString.push({ //modify the json we were passed in the data param

jquery mobile javascript verify json key

My mobile app reads an external json object. How can I check in javascript that a key node exists in the dynamically generated json structure? I tried the hasOwnProperty or containsKey methods, but without luck.
Example json data:
{ "element1":
{ "element2": { "Number": "0" },
"element3": { "Number": "1" },
"element4": { "Number": "2" }
}
}
As these elements are generated dynamically, I want to check if the key element3 exists in this structure. No luck with data.element1.hasOwnProperty("element3").
Yes, hasOwnProperty() method does not work for a Json object. It works for a Java Script Object. So You just need to convert this Json object into a Java Script Object using eval() method and check inside that object.
When you convert above Json structure, it will create an Object (element1) inside another Object (say JSObject). element1 will contain properties element2, element3 and element4. So your code should go like this.
var MyObject={ "element1":
{ "element2": { "Number": "0" },
"element3": { "Number": "1" },
"element4": { "Number": "2" }
}
}
var JSObject=eval('(' + MyObject+ ')');
var IsExistElement3 = JSObject.element1.hasOwnProperty("element3");

Categories