Why this JSON object cannot be parsed? - javascript

In my JavaScript file,
The declaring and json parse for the ajax response text is like this:
var subcats = JSON.parse(this.responseText);
The supposed responseText for the parsing is like this:
{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"}{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}
and it gives me this error:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 64 of the JSON data
what's the syntax error? help

Your JSON have multiple elements and therefore should be wrap in an Array/List like this
[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"}{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]
Hope it helps

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. So you can use it like this if you have a single item:
JSON.parse('{"presubcatId":"1", "precatId":"1", "presubcatName":"HR Manager"}');
but in your case you have multiple items that should be wrapped inside brackets [] and separated by commas or there is SyntaxError:
JSON.parse('[{"presubcatId":"1", "precatId":"1", "presubcatName":"HR Manager" }, { "presubcatId": "2", "precatId": "1", "presubcatName": "Marketing Manager"}]');
var string = '[{"presubcatId":"1", "precatId":"1", "presubcatName":"HR Manager" }, { "presubcatId": "2", "precatId": "1", "presubcatName": "Marketing Manager"}]';
var json = JSON.parse(string);
console.log(json);

Your JSON is invalid. You need change it like this:
[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"},{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]

your JSON data is invalid so that you are having problem,
var temp=[];
temp=[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"},{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]
console.log(JSON.stringify(temp))

Your JSON have multiple elements. So it must be treated like Array. See below image.
Below is valid JSON structure.
[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"},{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]

Your json object is not a valid json. You can check it on this site. It helps me a lot when I need to format or validate a Json object.
https://jsonlint.com/
Here is your json object formatted and it says what you are missing.

Related

How to handle escaped sequences in JSON array with express

I am using node.js with express and I'm building an API that exposes an endpoint that must accept POST requests with a a JSON array of strings.
I'm having problems when I receive JSON arrays with special escaped characters like this one:
[\t"hello"\n, "world"\n\n]
Is there any way to ignore or parse this with express? I thought that app.use(express.json()); could handle this.
Everytime I receive one JSON array with escape characters it gives me this error:
SyntaxError: Unexpected token \ in JSON at position 1
at JSON.parse (<anonymous>)
at parse (...\node_modules\body-parser\lib\types\json.js:89:19)
Show me the code creating the JSON. Then I'll help you solve the problem, because working with existing JSON like that isn't right. JSON only should have something like:
{
"name1": "value1",
"name2": "value2",
"name3": "value3",
...,
"namex": "valuex"
}
Never let values go outside the quotemarks if they're a string.
Maybe the json returned in response api is string so looks like that => [\t"hello"\n, "world"\n\n].
Do you parse it already?
const array = `[\t"hello"\n, "world"\n\n]`
const parseArray = JSON.parse(array)
console.log(parseArray)

json array encode in php and decode in javascript

I have this JSON encoded with PHP:
{
"id": "37",
"user_id": "1",
"account": "ssdv",
"amount": "5002",
"subject": "\u0647\u062f\u06cc\u0647",
"tags": "[{\"ttt\"}]"
}
the php array for above json was:
array (
'id' => '37',
'user_id' => '1',
'account' => 'ssdv',
'amount' => '5002',
'subject' => 'هدیه',
'tags' => '["ttt"]',
)
tags index is read from MySQL table with JSON datatype, so I can't change format of tags it have to be json array.
I've tried to decode first string as json by this code:
<script>
var obj = JSON.parse('{"id":"37","user_id":"1","account":"ssdv","amount":"5002","subject":"\u0647\u062f\u06cc\u0647","tags":"[{"ttt"}]"}');
</script>
but it throws this error:
Uncaught SyntaxError: Unexpected token t in JSON at position 86 at JSON.parse (<anonymous>)
how can i parse this json as a valid json in javascript?
update
my table is like this:
id user_id account amount subject tags
37 1 ssdv 5002 هدیه ["ttt"]
tags field is MySQL json type.
I fetch this record and try to json_encode it, the tags index turns to "tags":"[{"ttt"}]" after encode. but it cause error when i try to JSON.parse(myEncodedRecord). it looks the tags have to be like this "tags":["ttt"]. I know I can achieve this by preg_replace() , but is there any better way?
JSON.parse('{"id":"37","user_id":"1","account":"ssdv","amount":"5002","subject":"\u0647\u062f\u06cc\u0647","tags":["ttt"]}');
If tags are array why you need {}. I removed them and I was able to parse.
This worked for me in the console. It is safe to use parsing inside a try
if tags is a single entity like if we have 3 tags and we need to show only it's name we can simply put it as an array. only if we need to display multiple attributes we need to fetch it as an array of objects.
in first situation it will be like
"tags":["tag1name", "tag2name","tag3name"]
if it has multiple attributes
"tags":[{"name":"tag1name","type":"type1"},{"name":"tag2name","type":"type2"},{"name":"tag3name","type":"type3"}]
You can validate your JSON syntax with the help of the below website
https://jsonformatter.curiousconcept.com/
You have 2 issues in your JSON String:
1.) You cannot use array as a string. So please change the string "[{"ttt"}]" to [{"ttt"}].
2.) When you are initializing an object, you cannot specify an index alone. You should also specify the value. So in the above point notice the object initialization in the array. If you provide only one string it will consider that as the index not the value. This is javascript not PHP.
So you can either:
1.) Change the `[{"ttt"}]` to `[{"ttt":"test"}]`. That should work or
2.) Change the `[{"ttt"}]` to `[{"value":"ttt"}]` however you feel comfortable.
I have considered the first option so your result string is:
var txt = '{"id":"37","user_id":"1","account":"ssdv","amount":"5002","subject":"\u0647\u062f\u06cc\u0647","tags":[{"ttt":"test"}]}'
Try this out and let me know if you face any issues.
Hope This Helps.
to avoid this error I had to decode tags field value first, then encode the whole array
code:
//get the record
$record = $this->db->get_where('table', ['id' => $id])->row_array();
//decode tags value
$record['tags'] = json_decode($expense['tags']);
//encode and use
$record = json_encode($record);
now it's a standard JSON.

JSON parse functions are not parsing

I am running a Javascript function on the latest version of Mozilla which receives a string which I want to convert to a JSON object. The conversion seems to be failing.
The string is being generated on the server side in a Java function:
result = "[{ \"userID\": 1 \"firstName\":\"John\" \"lastName\":\"Sheridan\" }{ \"userID\": 2 \"firstName\":\"Michael\" \"lastName\":\"Geribaldi\" }]";
(note that I am attempting to return an array of values for a list).
The code on the client side is the ajax callback shown below:
var successFunc = function(data, textStatus, jqXHR)
{
alert("Data: "+data);
var obj = $.parseJSON(data);
alert("Object: "+obj);
}
Apparently, the data is coming back to the callback and is being displayed in its string form, but the JSON parser is failing because the second alert is failing to appear. I am sure something is wrong with my string but am having trouble figuring out what. The debugger is not telling me anything, I am just seeing a silent failure.
I have also attempted this using the JSON.parser() function. I am seeing the same thing. I am making a mistake somewhere. Can someone tell me where?
Your json is not valid, you are missing comma
In order to parse your json should be like this
[
{ "userID": 1, "firstName":"John", "lastName":"Sheridan" },
{ "userID": 2, "firstName":"Michael", "lastName":"Geribaldi" }
]
JSON is a format where data is in key:value pairs separeted by , and key and value are enclosed in double quotes, where objects are enclosed in {} braces and array is enclosed in [] hope you have got the your mistake that where your json is lacking.
"[{
\"userID\": 1 ,
\"firstName\":\"John\",
\"lastName\":\"Sheridan\",
},
{
\"userID\": 2 ,
\"firstName\":\"Michael\",
\"lastName\":\"Geribaldi\" }]"

javascript JSON response formatting

Folks,
Trying to understand returning and forming JSON responses.
The following code returns the object as a single string:
res.send(JSON.stringify(data));
Output to the browser:
{"Count":1,"Items":[{"dbsource":{"S":"x"},"number":{"S":"5002820"},"name":{"S":"blah,foo"},"expiration":{"S":"06/13/2015"},"type":{"S":"bar"}}]}
Dont I want the JSON output to be more readable, ie :
{
"one": "two",
"key": "value"
}
What should i change JSON.stringify(data) to? Ideally I want the response to be used as an API endpoint.
Thanks!
You are almost there. Use stringify with spaces
var str = JSON.stringify(data, undefined, 2);
The above string will have indentation with 2 spaces.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

JSON.parse parsing JSON with nested objects

I'm attempting to parse a JSON string with nested objects received in the response of a post request. After running JSON.parse(responseText), the result is in the following format:
[{
"atco":"43000156407",
"location":{
"longitude":"-1.7876500000000000",
"latitude":"52.4147200000000000","
timestamp":"2013-03-19 11:30:00"
},
"name":"Solihull Station Interchange",
"road":"STATION APPROACH",
"direction":"NA",
"locality":"Solihull",
"town":"Solihull"}, ...
I thought I would then be able pull values out using the following as an example, but all I get is undefined.
var atco = json[0].atco;
I've also tried json[0][0] but that returns an individual character from the JSON ([) . Does this indicate the JSON hasn't parsed correctly, or is this expected behaviour and I'm just referencing incorrectly?
This means that your JSON is being double encoded. Make sure you only encode it once on the server.
As proof, after you've parsed it, parse it again.
var parsed = JSON.parse(resposneText);
var parsed2 = JSON.parse(parsed);
alert(parsed2.atco);
Either that, or you're parsing it but then trying to select the data from the original string. This would obviously not work.

Categories