Json key has '#' Special character - javascript

Currently I need the URL for an image and I am getting it through the JSON file. I am not sure to acquire the key that has the URL due to the key having a # at the start. Here is the JSON:
{
"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png",
"size":"small"
},
{
"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png",
"size":"medium"
}

Same as with every other time you encounter some JSON string!
The # is an invalid character in a property name, work around is the bracket notation: «object»[property] --> «array»[index]['#text'].
We can use forEach to extract the results.
var string = '[{"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"small"},{"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"medium"}]';
var parsed = JSON.parse(string);
//parsed is an array, we can loop over it
parsed.forEach(function(obj) {
console.log(obj['#text']);
});
Even prettier would be if you can select from the array based on size:
var string = '[{"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"small"},{"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"medium"}]';
function getImageUrlBySize(size, json) {
var parsed = JSON.parse(json);
return parsed.find(function(element) { //modern browsers only (no IE)
return element['size'] == size;
})['#text']; //add text here since find returns the full item
}
console.log(getImageUrlBySize('small', string));

Related

How to split into valid array

I've following object that is return from API and I want to convert them into array either in javascript or c#.
[
"1":"h1:first",
"2":".content a > img",
"3":"#content div p"
]
I've tried converting that to json object, split function etc but din't working for me.
It throws exception Uncaught SyntaxError: Unexpected token : while using split function in javascript.
You can convert it to valid JSON by replacing the square brackets with curly braces.
var data = '["1":"h1:first","2":".content a > img","3":"#content div p"]';
var json = `{ ${data.trim().slice(1, -1)} }`;
Then JSON.parse it like you had tried earlier. And if you want an array, and don't care about the actual index numbers, you can use Object.values to get the Array of values.
var data = '["1":"h1:first","2":".content a > img","3":"#content div p"]';
var json = `{ ${data.trim().slice(1, -1)} }`;
console.log(json);
var parsed = JSON.parse(json);
console.log(parsed);
var array = Object.values(parsed);
console.log(array);
I choose c# code to fix the issue instead client-side (as suggested by #rock star below).
string[] domSelectors = selectors.Replace("\"", "").Split(new string[] { "[", ",", "]" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var domSelector in domSelectors)
{
string[] arrayElements = domSelector.Split(':');
string selector = string.Join(":", arrayElements.Skip(1));
}
Hope it helps others who don't have control over API and want to fix the issue as I'd in my project!

Get first word of string inside array - from return REST

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);

How to pass array with slashes or special characters?

I'm using the jquery get() function to send data. The data was array with information that can have special characters like / , ? and " . When this happens i can't access to url because the characters spoil the link.
How can i solve that? I did this:
function exemple()
{
$('.add').click(function(e)
{
var kitFamilia = $('#select-family').val();
var kitReference = $('#referenceinput').val();
var kitDescription = $('#descriptioninput').val();
var kitModel = $('#model-input').val();
var supplier = $('#select-supplier').val();
var details = [];
//alert(data);
details.push({stamp: stamp,family: kitFamilia, reference: kitReference, description: kitDescription, model: kitModel, supplier: supplier});
details = JSON.stringify(details, null, 2);
//alert(details);
$.get("/management-kit/create-kit/"+details, function(data)
{
location.reload();
});
e.preventDefault();
});
}
You should encode the data with encodeURIComponent
$.get("/management-kit/create-kit/"+encodeURIComponent(details), ..
Keep in mind that you are sending the JSON encoded as part of the path and not as a parameter. (and you might also want to remove the 2 space formating of the JSON as it will make the url quite longer)

How can I use underscore in name of dynamic object variable

Website that I'm making is in two different languages each data is saved in mongodb with prefix _nl or _en
With a url I need to be able to set up language like that:
http://localhost/en/This-Is-English-Head/This-Is-English-Sub
My code look like that:
var headPage = req.params.headPage;
var subPage = req.params.subPage;
var slug = 'name';
var slugSub = 'subPages.slug_en';
var myObject = {};
myObject[slugSub] = subPage;
myObject[slug] = headPage;
console.log(myObject);
Site.find(myObject,
function (err, pages) {
var Pages = {};
pages.forEach(function (page) {
Pages[page._id] = page;
});
console.log(Pages);
});
After console.log it I get following:
{ 'subPages.slug_en': 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Is you can see objectname subPages.slug_en is seen as a String insteed of object name..
I know that javascript does not support underscores(I guess?) but I'm still looking for a fix, otherwise i'll be forced to change all underscores in my db to different character...
Edit:
The final result of console.log need to be:
{ subPages.slug_en: 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Insteed of :
{ 'subPages.slug_en': 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Otherwise it does not work
The reason you are seeing 'subPages.slug_en' (with string quotes) is because of the . in the object key, not the underscore.
Underscores are definitely supported in object keys without quoting.
Using subPages.slug_en (without string quotes) would require you to have an object as follows:
{ subPages: {slug_en: 'This-Is-English-Sub'},
name: 'This-Is-English-Head' }
Which you could set with the following:
myObject['subPages']['slug_en'] = subPage;
Or simply:
myObject.subPages.slug_en = subPage;

JQuery - How to loop through JSON using each

I have cached the JSON returned from an Ajax call and need to loop through this to display it. I get the error, 'Cannot read property 'title' of undefined'. Can anyone help?
$.each(cache['cat-'+cat], function(i, jd) {
var title= jd.title; //issue is here
)}
When I console.log(cache['cat-'+cat]) I get the below:
Object {
date: "2016-07-28T15:08:03.596Z",
data: '[{"id":471,"title":"Lines and Calls","solution_areas":"lines-calls"}]'
}
When I console.log(jd) within the loop I get the below:
2016-07-28T15:13:14.553Z
if I use console.log(jd.data); I get
undefined
I have tried the below but they don't work either:
var title= jd.data.title;
var title= jd.data[0].title;
Can anyone tell me what I am doing wrong?
The way you are currently using it, each is going to iterate over every property of the cache['cat-'+cat] object, of which there are two, date and data.
So your anonymous function function(i, jd)will be called twice. The first time, jdwill be the value of the date property (a string), the second time it will be the value of the data property (also a string, that happens to be formatted as JSON).
The contents of data need to be parsed before they can be accessed as an object/array, and given that data is formatted as an array, I am guessing that you actually want to iterate over that. Given the example provided, I would change it to:
$.each(JSON.parse(cache['cat-'+cat].data), function(i, jd) {
var title= jd.title;
});
You aren't accessing it properly. And since cache['cat-'+cat] is already the needed object, what's the purpose of $.each? Should be
var title= JSON.parse(cache['cat-'+cat].data)[0].title;
(because the title is in the data, and the data is JSON).
Demo:
var obj = {
date: "2016-07-28T15:08:03.596Z",
data: '[{"id":471,"title":"Lines and Calls","solution_areas":"lines-calls"}]'
};
var title= JSON.parse(obj.data)[0].title;
console.log(title);
Just need to understand what is JSON and what is STRING
cache['cat-'+cat].data return a string that need to convert to JSON before pass to each loop:
var dataCacheReturned = cache['cat-'+cat];
var objCache = dataCacheReturned.data; //Its return a string
objCache = JSON.parse(objCache); //Parse string to json
$.each(objCache, function(i, jd) {
var title = jd.title;
console.log(title);
});

Categories

Resources