JSON.parse error....unexpected token{ from 2nd - javascript

My JSON.parse is successful when it is called first. But from 2nd call, unexpected token error occurs.
I found from the search in stackoverflow some explanation for other's question below..
"If you parse it again it will perform a toString-cast first so you're parsing something like "[object Object"] which explains the unexpected token o "
How can i make the fresh parse. my code is like below.
var musicEntry="";
function parsing(){
...
for(var i=0;i<musicList.length;i++){
musicEntry=musicEntry+ '{"fileName":"'+musicList[i].title+'"},';
}
.....
var musicJsonObjString='{"music":['+ musicEntry +']}';
musicJsonObj=JSON.parse(musicJsonObjString);
}

I'd recommend using JSON.stringify() instead of trying to write your own JSON encoder. Whilst your approach might now work with the trailing comma issue fixed, you'll also need to guard against reserved characters in your music title attribute.
Simply build a JavaScript object (or array) and give it to JSON.stringify(obj)
Working example
var musicList = [{
title: 'foo'
}, {
title: 'bar'
}];
var array = [];
for (var i = 0; i < musicList.length; i++) {
array.push({fileName: musicList[i].title})
}
var musicJsonObjString = JSON.stringify({music: array});
var musicJsonObj = JSON.parse(musicJsonObjString);
console.log("music", musicJsonObj);

You need to remove last comma from your array:
var musicJsonObjString='{"music":[' + musicEntry.substr(0, musicEntry.length - 1 ) + ']}';

Related

Using string interpolation in React.js regex function

I am having some issues using string interpolation in a regex, however I have also tried to log it to the console and I can see that I am doing it incorrectly.
I am trying to loop through an array of weather types to see if my API request returned a type of weather which requires me to add a class to one of my elements in the UI.
I iniitally thought the issue was using array[x] in the regex, but I have assigned this to a variable p and am still getting the same result.
let weatherTypes = ['rain', 'clouds', 'snow', 'clear', 'thunderstorm'];
for (var x= 0; x <= weatherTypes.length; x++) {
let p = weatherTypes[x];
console.log(p)
var searchPattern = `/${p}/i`;
var result = this.state.description.match(searchPattern);
console.log(`splash--weather-${p}`);
if(result !== null) {
var element = document.getElementById("splashContact");
element.classList.add(`splash--weather-${weatherTypes[0]}` );
}
}
The logic to add the class works when I abstract it out of the for loop so I know that part is working fine.
Can somebody please point me in the right direction?
edit Have now used backticks instead of quotation marks
searchPattern is a string so you just need to use the RegExp constructor before using it.
var searchPattern = `${p}/i`;
var searchPatternRegex = RegExp(`${searchPattern}`);

Is there a way to replace text from a JSON object after it has been stringified?

I have some JSON data which contains some urls. I'm extracting these urls from the json by looping through the objects which works fine. The urls however have 'page: ' pre-pended to them which i am trying to replace with 'https://'.
I can't get the replace property to work and give me the same result each time.
I've tried using the replace() property in different way and am using the console.log to view my results. I've also tried to stringify the JSON as I hear this is a good thing to do in order to handle it.
Each time i'm still seeing the 'page: ' word and it hasn't been replaced.
function showTopArticles(jsonObj) {
var getEntries = jsonObj.feed.entry;
var stringified = JSON.stringify(getEntries);
console.log(getEntries);
for (var i = 0; i < getEntries.length; i++) {
var list = document.createElement('article');
var articleTitle = document.createElement('li');
var articleUrl = document.createElement('a');
articleTitle.textContent = getEntries[i].title.$t;
articleUrl.textContent = getEntries[i].content.$t;
articleUrl.textContent.replace("page: ", "https://");
console.log(articleUrl.textContent);
list.appendChild(articleTitle)+list.appendChild(articleUrl);
section.appendChild(list);
}
}
I expect the output url to be 'https://www.google.com' but instead im seeing 'page : www.google.com'
replace() returns a modified value, it does not modify the original string.
You want something like:
articleUrl.textContent = articleUrl.textContent.replace("page: ", "https://");

How to get the 'Value' using 'Key' from json in Javascript/Jquery

I have the following Json string. I want to get the 'Value' using 'Key', something like
giving 'BtchGotAdjust' returns 'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
Wow... Looks kind of tough! Seems like you need to manipulate it a bit. Instead of functions, we can create a new object this way:
var jsonstring =
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},];
var finalJSON = {};
for (var i in jsonstring)
finalJSON[jsonstring[i]["Key"]] = jsonstring[i]["Value"];
You can use it using:
finalJSON["BtchGotAdjust"]; // Batch Got Adjusted
As you have an array in your variable, you have to loop over the array and compare against the Key-Property of each element, something along the lines of this:
for (var i = 0; i < jsonstring.length; i++) {
if (jsonstring[i].Key === 'BtchGotAdjust') {
console.log(jsonstring[i].Value);
}
}
By the way, I think your variable name jsonstring is a little misleading. It does not contain a string. It contains an array. Still, the above code should give you a hint in the right direction.
Personally I would create a map from the array and then it acts like a dictionary giving you instantaneous access. You also only have to iterate through the array once to get all the data you need:
var objectArray = [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"}]
var map = {}
for (var i=0; i < objectArray.length; i++){
map[objectArray[i].Key] = objectArray[i]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See js fiddle here: http://jsfiddle.net/t2vrn1pq/1/

Create JSON string from javascript for loop

I want to create a JSON string from a javascript for loop. This is what I tried to do (which gives me something that looks like a JSON string), but it does not work.
var edited = "";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
It gives me this:
"type":"empty","name":"email-address","realname":"Email Address","status":"empty","min":"empty","max":"empty","dependson":"empty",
This does not work if I try to convert it into a JSON object later.
Two problems:
You want an object, so the JSON string has to start with { and end with }.
There is a trailing , which may be recognized as invalid.
It's probably better to use a library, but to correct your code:
Change var edited = ""; to var edited = "{"; to start your JSON string with a {
Add edited = edited.slice(0, -1); after the for loop to remove the trailing comma.
Add edited += "}"; after the previous statement to end your JSON string with a }
Your final code would be:
var edited = "{";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
edited = edited.slice(0, -1);
edited += "}";
Again, it's best to use a library (e.g. JSON.stringify) by making an object with a for loop, adding properties by using POST[i].name as a key and POST[i].value as the value, then using the library to convert the object to JSON.
Also, you are starting with index 1 and ending with index POST.length-2, therefore excluding indices 0 (the first value) and POST.length-1 (the last value). Is that what you really want?
//dummy data
var post=[{name:'name1',value:1},{name:'name2',value:2}];
var json=[];
for(var i=0;i<post.length;i++)
{
var temp={};
temp[post[i].name]=post[i].value;
json.push(temp);
}
var stringJson = JSON.stringify(json);
alert(stringJson );
http://jsfiddle.net/3mYux/
You have extra comma in your JSON string. JSON string format: {"JSON": "Hello, World"}
var edited = "{";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
// remove last comma:
edited = edited.substring(0, edited.length-1) + "}";
Can't you just build up a hash and do toString on the hash? Something like this:
var edited = {};
for(var i=0;i<POST.length-1;i++) {
edited[POST[i].name] = POST[i].value;
}
Or maybe JSON.stringify is what you are looking for: http://www.json.org/js.html

How can I print javascript objects?

I have an object
var object= {}
I put some data in the object and then I want to print it like this
document.write(object.term);
the term is a variable that changes depending on different situations. When I try printing this it comes up with undefined.
How would it be done?
Update:
this is the code I am dealing with. I guess it probably isn't the same as what I said above because I am doing it in selenium with browsermob, I just thought it would be similar to document.write(). Here is the code
var numCardsStr = selenium.getText("//div[#id='set-middle']/div[2]/h2");
var numCards = numCardsStr.substr(4,2);
browserMob.log(numCards);
var flash = {}
for(i=0; i<(numCards); i++){
var terms = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[1]");
var defs = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[2]");
flash[terms] = defs;
browserMob.log(flash.terms);
}
EDIT: You're using two different variable names, flash and flashcards. I don't know if they are meant to be the same thing, but you are setting the value using the [] notation, then getting it using . notation.
Try:
var flash = {};
...
flash[terms] = defs;
browserMob.log(flash[terms]);
If term is a variable to represent the property you are retrieving, then you should use the square bracket notation for getting the property from the object.
Example: http://jsfiddle.net/xbMjc/ (uses alerts instead of document.write)
var object= {};
object.someProperty = 'some value';
var term = "someProperty";
document.write( object[term] ); // will output 'some value'
If you're using document.write(), there's a good chance you are trying to reference the object before it's been instantiated. My advice: don't use document.write() unless you need it in a template. For all other purposes, wait till the page loads and then run your script as an event handler.
There could be other reasons for the failure, but your code sample isn't complete enough for a diagnosis.
To output the whole object as text, use a JSON library:
<script type="text/javascript" src="http://www.JSON.org/json2.js"></script>
.
var o = { "term": "value" };
document.write(JSON.stringify(o, null, 4));
This will output the object as a string and indent 4 spaces to make it easy to read.
What you do is this:
var terms = "abcd";
var defs = "1234";
var flash = {};
flash[terms] = defs;
This creates this object:
{
"abcd": "1234"
}
If you want to go through the properties (i.e. "abce"), do this:
for (var key in flash) {
document.write('Key "' + key + '" has value "' + flash[key] + '"<br/>');
}
This will output:
Key "abcd" has value "1234"
Because I haven't seen this mentioned yet:
var a = {prop1:Math.random(), prop2:'lol'};
a.toString = function() {
output = [];
for(var name in this) if(this.hasOwnProperty(name) && name != 'toString') {
output.push([name, this[name]].join(':'));
}
return "{\n"+output.join(",\n\t")+"\n}";
};
document.write(a);
// should look like:
/*
{
prop1:0.12134432,
prop2:lol
}
*/
In the case that you're defining an object class, like MyObj:
var MyObj = function(id) {
this.someIdentity = id;
};
MyObj.prototype.toString = function() {
return '<MyObject:'+this.someIdentity+'>';
};
And then anytime you write something like
document.write(new MyObject(2));
It'll appear as <MyObject: 2>.
Avoid document.write
If you use Firefox, install firebug and use it's console api
The same console apis should work in chrome too.
For IE, get companion js
In javascript, obj.propertyname is used if the property name is known before hand. If it's not, then:
if pn contains the property name, obj[pn] should give you the value.
Well in firefox and in Chrome/Safari you could simply use...
var myObj = {id: 1, name: 'Some Name'};
window.console.log(myObj);
And the console will output something like "Object"
If you are in Chrome you could inspect the internal values of the object with ease using the built in developer console.
If you use firefox the output should come out of firebug as well...
I'm stating this as an alternative of using document.write as it seems a little bit invasive to me to output content on the document...

Categories

Resources