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

{
"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.

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

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.

Large JSON String not parsing using JSON.parse or angular.fromJson

I'm trying to replace the angularjs POST query with standalone JSON response string.
When angular GET / POST queries returns a response automatically converted to JSON and the code was working like charm.
Now, I'm trying to have the json response stored as a javascript string variable in the controller and then trying to parse it using JSON.stringify() and subsequently using JSON.parse().
There is no error but the resulting json object's member variables can't be accessed using the . operator
var staticData = '{"someKey":"someValue", "masterJobs":[]}'; //very large json string.
var resultString = JSON.stringify(staticData);
$scope.staticTestData = JSON.parse(resultString);
console.log($scope.staticTestData.masterJobs); // this displays 'undefined'
Controller function with the large JSON is available here.
You already have a string, so there is no need to use JSON.stringify.
Just use the following code:
var staticData = '{"someKey":"someValue", "masterJobs":[]}'; //very large json string.
$scope.staticTestData = JSON.parse(staticData);
console.log($scope.staticTestData.masterJobs);

How to get an inner object literal value with javascript

After calling console.log(JSON.stringify(req.params)), I get a string with the following structure:
{"q":"{\"email\":\"mymail#mail.com\"}","apiKey":"1234"}
With console.log(req.params.q), I have this result: {"email":"mymail#mail.com"}.
But I get "undefined" if I try to view the email value with console.log(req.params.q.email) or console.log(req.params.q["email"])
What is the best approach to get that value?
You must JSON.parse that inner part :
var test = {"q":"{\"email\":\"mymail#mail.com\"}","apiKey":"1234"};
alert(JSON.parse(test.q).email);
alerts mymail#mail.com
Why?
Because test holds an javascript object where q holds a string, So you must parse that string if you want to extract the JSON values from that string.
It looks like req.params.q is a string: "{\"email\":\"mymail#mail.com\"}".
You need to parse that json then fetch the value.
req = {params: {"q":"{\"email\":\"mymail#mail.com\"}","apiKey":"1234"}}
JSON.parse(req.params.q)
> Object {email: "mymail#mail.com"}
JSON.parse(req.params.q).email
> "mymail#mail.com"

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