json array encode in php and decode in javascript - 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.

Related

How do I access the value of an array property?

How do I access the value stored in the description property using javascript?
As seen in the image below (a screenshot from the browser console), the stored value is [STK_CB - ] Request Cancelled by user
In the browser console, I have tried console.log(responseMan.payload["0"].jsonPayload.description); which shows undefined. Where am I going wrong?
Looking forward to your help.
The value of jsonPayload is a string, not an object -- notice the double quotes around it. And the name of the property implies that it's JSON. You need to call JSON.parse() to convert it to an object.
var payload = JSON.parse(responseMan.payload[0].jsonPayload);
console.log(payload.description);
just remove " from index and do it like:
u also have to cast the json first
const jsonStr = responseMan.payload[0].jsonPayload;
const data = JSON.parse(jsonStr);
console.log(data.description);
The problem is in your json. Because you are trying to access responseMan.payload ["0"]. JsonPayload up there is a correct element in the json. But the description is a string value in responseMan.payload ["0"]. JsonPayload, therefore, must format the contents of responseMan.payload ["0"]. JsonPayload on a json object. Example var obj = JSON.parse (responseMan.payload ["0"]. JsonPayload); and so
description will be a json object
OR
You can fix that json in your backend and send that section as a json and not as a string

Why this JSON object cannot be parsed?

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.

JSON encoded Multidimensional array returns wrong syntax (Unexpected ])

I have an array of arrays in PHP that I need to send to javascript as JSON. The PHP script and AJAX call work, but the returned JSON string is not parse-able JSON; instead of an array of arrays, it just sticks the arrays together with no separators or container.
Example JSON String:
[{"id":"77","options":[],"price":"4.25","title":"Zeppoli's","spec":""}][{"id":"78","options":[],"price":"7.95","title":"Battered Mushrooms","spec":""}]
PHP Snippet that creates above JSON String:
$cartArr = array(); // array of objects to be jsonified
foreach($products as $product){
unset($newItem);
$newItem = array(
"id" => $product['itemID'],
"options" => $theseOptions,
"price" => $product['price'],
"title" => $product['name'],
"spec" => $product["special"],
"cartid" => $product['ID']
);
array_push($cartArr,$newItem);
echo json_encode($cartArr);
}
An attempt to JSON.parse() the string will result in the following error, unless the string is manually corrected.
Uncaught SyntaxError: Unexpected token [
You're building json in a loop, which means you're outputting MULTIPLE independent json strings, which is illegal syntax. e.g. you're doing
[0,1,2][3,4,5]
which is two separate arrays jammed up against each other. It would have to be more like
[[0,1,2],[3,4,5]]
to be valid JSON. You encode to json LAST, after you've completely build your PHP data structure, not piecemeal in the middle of the construction process.
e.g.
foreach(...) {
$array[] = more data ...
}
echo json_encode($array);

\ getting appended in the JSON response. How should i remove this

{
"content": "{\"text\":\"Executing NodeDatasetFileOrDirectoryCSV : 1\",\"id\":1,\"name\":\"CSV\",\"type\":\"text\"}"
}
\ tag is getting appended after everything.
I want to access the type field. But i am not able to even after content.type because of the \ appended after every element. How to remove this ?
You're response is coming down as a valid JSON object, but the content property holds a value that is a JSON string, not a JSON object. You can either fix it on your server-side however you are constructing your response, or you can use JSON.parse to parse the content JSON string into a full-fledged object in JavaScript after you get your response.
The latter would be something like this:
var response = {"content": "{\"text\":\"Executing NodeDatasetFileOrDirectoryCSV : 1\",\"id\":1,\"name\":\"CSV\",\"type\":\"text\"}" };
response.content = JSON.parse(response.content);
console.log(response.content.type);
Use JSON.parse() to get the JSON object from the string and then get the values using keys.

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