I'm getting AsyncStorage data but there i'm getting special character \ which was not there when i set the item. Don't know why this is being added. Anyway i'm trying to remove this character from my data. I have tried the following way to do that:
data = ["{\"word\":\"Cat\",\"pronunciation\":null,\"definitions\":[{\"type\":\"noun\",\"definition\":\"a small domesticated carnivorous mammal with soft fur, a short snout, and retractile claws. It is widely kept as a pet or for catching mice, and many breeds have been developed.\",\"example\":\"their pet cat\",\"image_url\":\"https://media.owlbot.info/dictionary/images/aaaaaaaaaaaaaaaaac.jpg.400x400_q85_box-42,0,943,900_crop_detail.jpg\",\"emoji\":\"🐈\"}]}",
var b=JSON.stringify(data);
var str = b.replace(/\\/g, '');
var final = JSON.parse(str);
console.log(final);
Now this throws error Unexpected token { in JSON at position 3 . How can i resolve this?
It looks like you might want to call JSON.parse with the elements within data, rather than data itself. The data variable is an array, but the elements within it are JSON. For example:
const data = [...];
const parsedData = data.map(datum => JSON.parse(datum));
Related
I have an array that comes in from from my API that I would like to arrange in a way that is better for the user (namely, in a column as opposed to the typical comma separated printed array).
This is my JS Fiddle to give a clearer picture: https://jsfiddle.net/2z89owas/
My question is, how can I get output3 to display just like output (and maintain its status as an iterable array like it was as dates)?
First you should not be using value for an html element. You can use .value for extracting value from inputs. Change your line to:
var val = document.getElementById('output2').innerHTML;
Afterwards, you have to split the same way you did join.
var dates3 = val.split('<br>');
document.getElementById('output3').innerHTML = dates3;
You can directly use join, something like:
document.getElementById('output3').innerHTML = dates.join(',');
You can try mapping over the contents of dates instead, as so:
let datesElem = dates.map(date =>`<p>${date}</p>`);
// test: console.log(datesElem)
document.getElementById('output3').innerHTML = datesElem
My problem is that I have to concatenate all the text after the "product_link_href": in a huge serie of things (there are 200+ of these so I couldn't post the entire thing) like:
Solved snippet removed for privacy reasons
It's coming from an api, it's white in windows power shell, the name of the thing is response.data I'm using axios; I think this thing to the machine is just plain text, because it was green before I selected it whit .data ; but I still need all the text after "product_link_href": concatenated, in text format and sepsarated by ","
The code I am using is
axios.get('https://randomapi/' + id + '/json?api_token=examplenotrealapitoken').then(response => {
console.log(response.data);
});
I tried JSON.parse and stringify but nothing works.
The response from the server is stringified JSON objects that have been concatenated with line return characters "\n".
It is not JSON parseable because it is not an array, which it needs to be, to be valid JSON.
The approach I took is to coerce it to "an array of stringified JSON objects". Since each object is shallow, there is no nesting, so the } character is unambiguously the end of a stringified object.
You can call massiveJSONishString.split('}'), and you get an array of JSON-stringified objects with the trailing } missing on each one.
Then you map over that array, and for each element, add the trailing } that we threw away to array-ify it, and JSON.parse() that string, producing an array of JSON objects.
This is the code you are looking for:
const textArray = res.data.split("}");
const jsonArray = textArray.map(element => {
try {
return JSON.parse(`${element}}`);
} catch (e) {
return {
product_link_href: "MALFORMED JSON"
};
}
});
// console.log(jsonArray);
const product_link_hrefs = jsonArray.map(obj => obj.product_link_href);
const list = product_link_hrefs.join(", ");
console.log(list);
console.log(`You're welcome!`);
I have this code:
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
This code will use localStorage.
Here is now the code to get the stored data:
var retrievedObject = localStorage.getItem('added-items');
My problem now is, how can i get the size of the data items? answer must be 2.
How can i get the "Item1" and "Item2"?
I tried retrievedObject[0][0] but it is not working.
And how to add data on it?
so it will be
{"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
Can I use JSON.stringify?
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
stringify means, take an object and return its presentation as a string.
What you have, is already a string and not a JSON object.
The opposite is JSON.parse which takes a string and turns it into an object.
Neither of them have anything to do with getting the size of an array. When properly coding JavaScript you almost never use JSON.parse or JSON.stringify. Only if serialization is explicitly wanted.
Use length for the size of the array:
var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
console.debug(obj.items.length);
// THIS IS ALREADY STRINGIFIED
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
// DO NOT STRINGIFY AGAIN WHEN WRITING TO LOCAL STORAGE
localStorage.setItem('added-items', string);
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('added-items');
// CONVERT STRING TO REGULAR JS OBJECT
var parsedObject = JSON.parse(retrievedObject);
// ACCESS DATA
console.log(parsedObject.items[0].Desc);
To bring clarity to future people that may stumble across this question and found the accepted answer to not be everything you hoped and dreamed for:
I've extended the question so that the user may either want to input a string or JSON into localStorage.
Included are two functions, AddToLocalStorage(data) and GetFromLocalStorage(key).
With AddToLocalStorage(data), if your input is not a string (such as JSON), then it will be converted into one.
GetFromLocalStorage(key) retrieves the data from localStorage of said key
The end of the script shows an example of how to examine and alter the data within JSON. Because it is a combination of objects and array, one must use a combination of . and [] where they are applicable.
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};
localStorage.setItem('added-items', AddToLocalStorage(string));
localStorage.setItem('added-items', AddToLocalStorage(json));
// this function converts JSON into string to be entered into localStorage
function AddToLocalStorage(data) {
if (typeof data != "string") {data = JSON.stringify(data);}
return data;
}
// this function gets string from localStorage and converts it into JSON
function GetFromLocalStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
var myData = GetFromLocalStorage("added-items");
console.log(myData.items[2].firstName) // "John"
myData.items[2].firstName = ["John","Elizabeth"];
myData.items[2].lastName = ["Smith","Howard"];
console.log(myData.items[2]) // {"firstName":["John","Elizabeth"],"lastName":["Smith","Howard"]}
console.log(myData.items.length) // 4
JSON.parse is definitely the best way to create an object but I just want to add if that doesn't work (because of lack of support), obj = eval('(' + str + ')'); should work. I've had a problem with a HTML to PDF converter in the past that didn't include JSON.parse and eval did the trick. Try JSON.parse first.
Access your object: obj.items[0].Desc;
var object = Json.parse(retrievedObject);
Now you can access it just like an array
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you need more help i have some previous code where i am reading Json from local storage and making a form from that json. This code will help in understanding how to traverse that array
Json stored in localstorage
{"form":[{"element":"input", "type":"text","name":"name","value":"value","min":"2","max":"10"}]}
JavaScript to read that json
function readJson(){
if(!form_created){
add_form();
}
var fetched_json = localStorage.getItem("json");
var obj=JSON.parse(fetched_json);
for(var i=0; i<obj.form.length;i++){
var input = document.createElement(obj.form[i].element);
input.name = obj.form[i].name;
input.value = obj.form[i].value;
input.type = obj.form[i].type;
input.dataset.min = obj.form[i].min;
input.dataset.max = obj.form[i].max;
input.dataset.optional = obj.form[i].optional;
form.insertBefore (input,form.lastChild);
}
alert(obj.form[0].name);
}
I have a full string consisting of something like this [(data1.1)(data1.2)][(data2.1)(data2.1)]
Ive read you can do something smart with match function and regex. I want two arrays with the data loaded out of the parentheses.. How in earth do i do that? Please use my string as example.
I came up with this abomination:
var array = s.replace(/^\[|\]$/g,'').split('][').map(function(a){
return a.replace(/^\(|\)$/g,'').split(')(')
});
http://jsfiddle.net/8kLhc/
Also if you deliberately save or transmit data like this then you should really have a look at JSON or proper database design.
I wasn't entirely sure what you were after, but I'm assuming this
var what = '[(data1.1)(data1.2)][(data2.1)(data2.2)]',
have = [],
you = [],
tried = /\[\(([^)]*)\)\(([^)]*)\)\]/g;
what.replace(tried, function (use, brain, forthis) {
you.push((have.push(brain), forthis));
});
console.log(have, you);
// ["data1.1", "data2.1"] ["data1.2", "data2.2"]
I am trying to write something that would look at tweets and pull up info about stocks being mentioned in the tweet. People use $ to reference stock symbols on twitter but I cant escape the $.
I also dont want to match any price mention or anything like that so basically match $AAPL and not $1500
I was thinking it would be something like this
\b\$[a-zA-Z].*\b
if there are multiple matches id like to loop through them somehow so something like
while ((tweet = reg.exec(sym_pat)) !== null) {
//replace text with stock data.
}
This expression gives me an unexpected illegal token error
var symbol_pat = new RegExp(\b\$[a-z]*);
Thanks for the help if you want to see the next issue I ran into
Javascript AJAX scope inside of $.each Scope
Okay, you've stated that you want to replace the matches with their actual stock values. So, you need to get all of the matching elements (stock ticker names) and then for each match you're going to replace the it with the stock value.
The answer will "read" very similarly to that sentence.
Assume there's a tweet variable that is the contents of a particular tweet you're going to work on:
tweet.match(/\b\$[A-Za-z]+\b/g).forEach(function(match) {
// match looks like '$AAPL'
var tickerValue = lookUpTickerValue(match);
tweet.replace(match, tickerValue);
});
This is assuming you have some logic somewhere that will grab the ticker value for the given stock name and then replace it (it should probably return the original value if it can't find a match, so you don't mangle lovely tweets like "Barbara Streisand is $ATAN").
var symbol_pat = new RegExp('\\b\\$[a-z]+\\b','gi');
// or
var symbol_pat = /\b\$[a-z]+\b/gi;
Also, for some reason JS can not calculate the beginning of a word by \b, it just catches the one at the end.
EDIT: If you're replacing the stock symbols you can use the basic replace method by a function and replace that data with predefined values:
var symbol_pat = /(^|\s)(\$[a-z]+\b)/gi;
var stocks = {AAPL:1,ETC:2}
var str = '$aapl ssd $a a$s$etc $etc';
console.log(str);
str = str.replace(symbol_pat, function() {
var stk = arguments[2].substr(1).toUpperCase();
// assuming you want to replace $etc as well as $ETC by using
// the .toUpperCase() method
if (!stocks[stk]) return arguments[0];
return arguments[0].replace(arguments[2],stocks[stk]);
});
console.log(str);