I'm having a bit of trouble wrapping my head around some JSON stuff. Namely, I'm trying to retrieve a string from a json response received from the google translate api i'm querying.
var translator = function () {
for (var i = 0; i < result.length; i++)
{
//Construct URI
var source =
'https://www.googleapis.com/language/translate/v2?' +
'key=MY-API-KEY-REMOVED-ON-PURPOSE&' +
'source=en&' +
'target=fr&' +
'q=' +
result[i][1]; //looping over an array, no problem there
//Receive response from server
var to_Translate =new XMLHttpRequest();
to_Translate.open("GET",source,false);
to_Translate.send();
var translated = to_Translate.responseText;
JSON.parse(translated);
translated = translated.data.translations[0].translatedText;
console.log(translated);
}
};
translator();
Where
console.log(translated);
yields
{
"data": {
"translations": [
{
"translatedText": "some stuff that's been translated"
}
]
}
}
My question is: how can i access the value of translatedText? I've tried:
translated.data.translations[0].translatedText;
But it doesn't seem to work. When I console.log this i get
Uncaught TypeError: Cannot read property 'translations' of undefined
translator
(anonymous function)
Let me know what you guys think!
That is just text you have to parse it with
JSON.parse(translated)
so you could access it with, for example, translated.data
UPDATE
The error you are getting means that translated.data is undefined, you have to assign the parse to a variable, otherwise it will never work, it doesn't modify it in place
var translated = JSON.parse(to_Translate.responseText);
Yes, Use
translated.data.translations[0].translatedText;
Hope it will work fine.
So close!
translated.data.translations[0].translatedText;
translations is an array of objects, and you want the translatedText property of the first element in the array.
UPDATE:
Just to confirm the output of to_Translate.responseText is a string containing:
{
"data": {
"translations": [
{
"translatedText": "some stuff that's been translated"
}
]
}
}
So you should be able to do:
var translated = to_Translate.responseText,
parsed = JSON.parse(translated),
text = parsed.data.translations[0].translatedText;
console.log(text);
Related
I try get the sessionid before REST function, but in the case if I does not convert toString(); show only numbers (21 22 2e ...).
See this image:
1º:
Obs.: Before using split.
!!xxxxxxx.xxxxx.xxxxxxx.rest.schema.xxxxResp {error: null, sessionID: qdaxxxxxxxxxxxxxj}
My code:
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxxxxx","password":"xxxxxxxx","platform":"xxxxx" },
headers: { "Content-Type": "application/json" }
};
client.registerMethod("postMethod", "xxxxxxxxxxx/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data); all return, image 1
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8'); // if i does not convert to string, return numbers, see image 1..
console.log(data); //all inside image 2, and i want just value from sessionid
var output = data;
var res = output.split(" "); // using split
res = res[4].split("}", 1);
}
console.log(res); //image 3
});
I tested with JSON.parse and JSON.stringify and it did not work, show just 'undefined' for all. After convert toString();, And since I've turned the values into string, I thought of using split to get only the value of sessionid.
And when I used split, all transform to array and the return is from console.log(data), see image 2:
2º:
Obs.: After use split and convert to array automatically.
And the return after use split is with the conditions inside my code:
3º:
And the return after use split is with the conditions inside my code:
[ 'bkkRQxxxxxxxxxxxxx' ]
And I want just:
bkkRQxxxxxxxxxxxxx
I would like to know how to solve this after all these temptations, but if you have another way of getting the sessionid, I'd be happy to know.
Thanks advance!
After converting the Buffer to a string, remove anything attached to the front with using data.substr(data.indexOf('{')), then JSON.parse() the rest. Then you can just use the object to get the sessionID.
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
data = data.substr(data.indexOf('{'));
obj = JSON.parse(data);
console.log(obj.sessionID);
}
EDIT:
The issue you are having with JSON.parse() is because what is being returned is not actually JSON. The JSON spec requires the properties to be quoted ("). See this article
If the string looked like this, it would work: {"error": null, "sessionID": qdaxxxxxxxxxxxxxj}
Because the json is not really json, you can use a regular expression to get the info you want. This should get it for you.
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
console.log(match[2]);
EDIT 2: After fully reading the article that I linked above (oops haha), this is a more preferable way to deal with unquoted JSON.
var crappyJSON = '{ somePropertyWithoutQuotes: "theValue!" }';
var fixedJSON = crappyJSON.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2": ');
var aNiceObject = JSON.parse(fixedJSON);
So, I have been trying to solve this all of yesterday and today but cannot figure it out. I have the following returned in a variable called
var myRequest = req.body
console.log(myRequest)
Produces the following:
{
"methodcall": {
"methodname": ["userLogin"],
"params": [{
"param": [{
"value": [{
"string": ["test1"]
}]
}, {
"value": [{
"string": ["password"]
}]
}]
}]
}
}
Now, I need to access the params key, and access the first param value so that whatever is returned in the first param value string is stored as username in a variable, and whatever is returned in param value string (the second one), is stored as a password.
So the final effect something like this:
var username = myRequest.methodcall.params.param...first value string
var password = myRequest.methodcall.params.param...second value string
However, I am really struggling to understand how to do this. Im guessing forEach loops would come in this, however I do not have experience with them so would appreciate some tips.
Also, when I try doing myRequest.methodcall, I keep getting undefined returned.
Any help will be greatly appreciated!
It sounds like your value is in JSON, parse it first and then you should presumably be able to get its values:
var myRequest = JSON.parse(req.body);
var userName = myRequest.methodcall.params[0].param[0].value[0].string[0];
var password = myRequest.methodcall.params[0].param[1].value[0].string[0];
What you have posted is JSON. you need to set it up like:
var myRequest = JSON.parse(req.body)
this will allow you to access the it like a normal js object.
Use . to access keys in object and [] to access index in array.
This code should work:
var username = myRequest.methodcall.params[0].param[0].value[0].string[0]
If you would like to use a loop at get the values test1,password, and so on. You can use a loop and access the param array:
var params = myRequest.methodcall.params[0].param;
params.forEach(function(item){
console.log(item.value[0].string[0]);
});
Fiddle
//var myRequest = JSON.parse(req.body) // if JSON
var myRequest = {
"methodcall": {
"methodname": ["userLogin"],
"params": [{
"param": [{
"value": [{
"string": ["test1"]
}]
}, {
"value": [{
"string": ["password"]
}]
}]
}]
}
};
var params = myRequest.methodcall.params;
var uname, pwd;
for (var i = 0; i < params.length; i++) {
console.log("uname is " + params[i].param[0].value[0].string);
console.log("pwd is " + params[i].param[1].value[0].string)
}
if your response structure will be same then no need to go for loop or something, just directly access the username and password from response.
try this.
var username = myRequest.methodcall.params[0].param[0].value[0].string[0];
var password = myRequest.methodcall.params[0].param[1].value[0].string[0];
Did you debug your code?
I mean these code:
var username = myRequest.methodcall.params.param[0];
var password = myRequest.methodcall.params.param[1];
I've node application and Inside a folder I've txt file(long...) with content like following
BASH=/bin/sh
BASH_ARGC=()
BASH_ARGV=()
BASH_LINENO=([0]="0")
BASH_VERSINFO=([0]="3" [1]="2" [2]="51" [3]="1" [4]="release" )
BASH_VERSION='3.2.2(1)-release'
CF_INSTANCE_ADDR=10.2.7:501
CF_INSTANCE_INDEX=0
CF_INSTANCE_IP=10.97.27.7
CF_INSTANCE_P='[{external:500,internal:501}]'
COLUMNS=80
I read the txt file content with fs.readFile and I need to update some property there so I think to parse it to json but this is not working
my questions is:
Should I parse it to json? in order to modify some property value
such like
from
CF_INSTANCE_ADDR=10.2.7:501
to
CF_INSTANCE_ADDR=11.3.8:702
Or
CF_INSTANCE_P='[{external:500,internal:501}]'
to
CF_INSTANCE_P='[{external:100,internal:200}]'
Etc...
There is other better way?
This is what I tried
fs.readFile(filePath, 'utf8').then(function (response) {
var aa = JSON.stringify(response);
//console.log(aa);
var bb = JSON.parse(aa);
console.log(bb);
return response;
}
You can convert the string to an object at which point you can decide how to proceed/tidy up the data:
var obj = {};
str.split(/\n/g).forEach(function (el) {
var spl = el.split('=');
obj[spl[0]] = spl[1];
});
DEMO
So you should be left with an object called obj:
var obj = {
"BASH": "/bin/sh",
"BASH_ARGC": "()",
"BASH_ARGV": "()",
"BASH_LINENO": "([0]",
"BASH_VERSINFO": "([0]",
"BASH_VERSION": "'3.2.2(1)-release'",
"CF_INSTANCE_ADDR": "10.2.7:501",
"CF_INSTANCE_INDEX": "0",
"CF_INSTANCE_IP": "10.97.27.7",
"CF_INSTANCE_P": "'[{external:500,internal:501}]'",
"COLUMNS": "80"
}
You can now access the values of each key using either dot or bracket notation:
obj.BASH_VERSION // '3.2.2(1)-release'
obj['BASH_VERSION'] // '3.2.2(1)-release'
Here I'll remove those single quotes from BASH_VERSION:
obj.BASH_VERSION = obj.BASH_VERSION.replace("'", "");
How do you reference a JSON object in JavaScript?
I have a JSON response from a Rest web service and trying to reference the contents of the response which I have parsed to JSON by way JSON.Parse(response)
Sample JSON:
{
"HotelListResponse":{
"customerSessionId":"",
"numberOfRoomsRequested":1,
"moreResultsAvailable":true,
"cacheKey":"",
"cacheLocation":"",
"cachedSupplierResponse":{
"#supplierCacheTolerance":"NOT_SUPPORTED",
"#cachedTime":"0",
"#supplierRequestNum":"101",
"#supplierResponseNum":"",
"#supplierResponseTime":"",
"#candidatePreptime":"14",
"#otherOverheadTime":"",
"#tpidUsed":"",
"#matchedCurrency":"true",
"#matchedLocale":"true"
},
"HotelList":{
"#size":"20",
"#activePropertyCount":"101",
"HotelSummary":[
{
"name":"name1"
},
{
"name":"name2"
}
]
}
}
}
How can I, for example reference the customerSessionId? And the second HotelSummary name?
For customerSessionId I have tried jsonObject.customerSessionId which returns undefined. For the second hotel summary name I have tried jsobObject.HotelList.HotelSummary[1].name which is undefined too.
Given the JSON string above parsed and assigned to a variable as such:
var response = JSON.Parse(jsonString);
you should be able to access it like this:
var customerSessionId = response.HotelListResponse.customerSessionId;
Here's the working solution fiddle
As you can see, you need to reference HotelListResponse,
so if your var result holds your json object, then you can fetch the values by using
var first = result.HotelListResponse.customerSessionId
var second = result.HotelListResponse.HotelList.HotelSummary[1].name
I want to encode a Javascript object into a JSON string and I am having considerable difficulties.
The Object looks something like this
new_tweets[k]['tweet_id'] = 98745521;
new_tweets[k]['user_id'] = 54875;
new_tweets[k]['data']['in_reply_to_screen_name'] = "other_user";
new_tweets[k]['data']['text'] = "tweet text";
I want to get this into a JSON string to put it into an ajax request.
{'k':{'tweet_id':98745521,'user_id':54875, 'data':{...}}}
you get the picture. No matter what I do, it just doesn't work. All the JSON encoders like json2 and such produce
[]
Well, that does not help me. Basically I would like to have something like the php encodejson function.
Unless the variable k is defined, that's probably what's causing your trouble. Something like this will do what you want:
var new_tweets = { };
new_tweets.k = { };
new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;
new_tweets.k.data = { };
new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';
// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);
You can also do it all at once:
var new_tweets = {
k: {
tweet_id: 98745521,
user_id: 54875,
data: {
in_reply_to_screen_name: 'other_user',
text: 'tweet_text'
}
}
}
You can use JSON.stringify like:
JSON.stringify(new_tweets);