I'm so lost in space right now. I've sat for like 2-3h to find a solution to this problem but i just keep failing. Maybe i've gone blind or something. I hate asking for help but i really need it right now.
I have a json-response from a page wich is in this format:
[Object { timestamp="2015-01-04 21:05:16", value="25.4"},
Object { timestamp="2015-01-04 21:10:27", value="25.3"},
Object { timestamp="2015-01-04 21:15:38", value="28.7"},
Object { timestamp="2015-01-04 21:20:49", value="33.5"}]
And i need for it to look like this:
[ [1183939200000,40.71],
[1184025600000,40.38],
[1184112000000,40.82],
[1184198400000,41.55],
[1184284800000,41.18],
[1184544000000,41.06]]
I have tried soo much stuff and i feel so stupid asking for this because its probably the easiest thing in the world.
Thank you in advance!
Edit:
Apparently what Im getting back from the call is:
[{"timestamp":"2015-01-04 21:05:16","value":"26.9"},
{"timestamp":"2015-01-04 21:10:27","value":"27.1"},
{"timestamp":"2015-01-04 21:15:38","value":"24.8"},
{"timestamp":"2015-01-04 21:20:49","value":"21.4"},
{"timestamp":"2015-01-04 21:26:01","value":"19.6"}]
I got the "object" one when i console.debug:ed it. Dont know if this makes any difference or not.
Thanks
Assuming that the second value in the array should be equal to the value member of the object:
arr = arr.map(function(obj) {
return [
Date.parse(obj.timestamp.replace(' ', 'T')),
+obj.value
];
});
The Date.parse function converts a string like "2015-01-04T21:05:16" to a JavaScript timestamp (ISO 8601 format). That's why your current format needs to be changed slightly.
Related
I'm receiving a string like obj{a="foo",b="bar",c=3,d=4.0} inside a nodejs environment I'm working in and I'm trying to convert this String into a reference-able Object like this:
{
a : "foo",
b : "bar",
c : 3,
d : 4.0
}
Assigned to obj of course.
I've used a myriad of formatting tricks but whenever I call JSON.parse() I get unexpected character errors. Usually on the first alpha-character it sees.
My next step is to write several nested loops to make all of the assignments manually but I'm hoping someone can point me in the right direction on how to parse this.
EDIT: Ok there's a little more to the story and I thought I should omit it but I guess explaining everything would be helpful.
The actual data packet that I'm receiving looks like this.
ack{a="000000061",b=0,c=2.0}\rb{a=244.0,b=255,c=4.0}\rc{a=6.0,b=55,c=55}endack;
So yeah that's the actual string I'm trying to parse into three distinct accessible Objects. I know I'm having a brain fart from a long day but yeah it's giving me a run for my money right now.
First replace the "=" with ":" and remove the obj infront
str = str.replace(/=/g, ":").replace("obj{", "{")
Since it's not in correct json format (but can be read by js parser) we can't use JSON.parse but we can use eval
eval("var obj = " + str);
Obvious there are some assumptions with this technique such that = always mean colon and you won't have obj{ as text (but the latter can be fixed with a simple substring method)
Keep in mind eval is also considered evil so use at your own risk. Imagine if the user were to send bad data, they could easily get into your parser and run something malicious. But hopefully this will give you an idea or inspiration to a better solution.
You can go a step further and use
str = 'obj{a="foo",b="bar",c=3,d=4.0}'
str = str.substr(3,str.length).replace(/([{,])([\w])=/g, '$1\"$2\":');
var obj = JSON.parse(str);
I haven't touched JavaScript in a while and thought since the Olympics are on currently, I could use the opportunity to play around with returning countries with at least 1 medal, etc. I am trying to find out, through Javascript, how many countries at the moment have got at least 1 medal in the Commonwealth Games. I am stuck at a point of getting the value from the class. To get to this point, on the tenplay.com.au website I have gone into the console and done:
var check = document.getElementsByClassName("medal-tally")[0].children[1].children[0];
check.getElementsByClassName("total");
This returns:
<td class="total" title="Total">165</td>
This is probably very very simple, but I have failed so far. I have tried .value, .className, checking if it returns true with == 165 and === "165", I believe these are all valid but I am a bit rusty as you can tell.
Thank you in advance for the help,
Daniel.
document.getElementsByClassName return an array like object. You can use index to fetch its element then You can use innerHTML property
Use
var text = check.getElementsByClassName("total")[0].innerHTML;
I've seen a lot of different answers to this question and have tried applying their code to my project but none of these solutions seem to work for the data I have.
I need to turn this output into several objects:
[{"creature":{"id":1,"name":"R.I.P.","sprite_location":null,"health_points":0,"attack":0,"defense":0,"action_points":0,"attack_cost":0}},{"creature":{"id":2,"name":"R.I.P.","sprite_location":"http://chunkofwhat.com/games/Parousia/sprites/rip.gif","health_points":0,"attack":0,"defense":0,"action_points":0,"attack_cost":0}},{"creature":{"id":3,"name":"Bull.","sprite_location":"http://chunkofwhat.com/games/Parousia/sprites/bull.gif","health_points":50,"attack":8,"defense":20,"action_points":9,"attack_cost":5}},{"creature":{"id":4,"name":"Swallow.","sprite_location":"http://chunkofwhat.com/games/Parousia/sprites/swallow.gif","health_points":30,"attack":12,"defense":10,"action_points":13,"attack_cost":5}},{"creature":{"id":5,"name":"Kappa.","sprite_location":"http://chunkofwhat.com/games/Parousia/sprites/kappa.gif","health_points":40,"attack":6,"defense":15,"action_points":9,"attack_cost":3}},{"creature":{"id":6,"name":null,"sprite_location":null,"health_points":null,"attack":null,"defense":null,"action_points":null,"attack_cost":null}}]
When I try jQuery.parseJSON(), it just gives me a bunch of [object Object]s but I can't refer to creature[1].id etc.
Again, I know this is a frequently asked question. I really have been through many other examples but they just didn't work out for me.
Thank you.
Each object has one property (creature) with another object as it's value.
result_of_parsing_json[1].creature.id
var creatures = JSON.parse('big_json_string');
for (var i = 0; i < creatures.length; i++) {
var creature = creatures[i].creature; // this is how your object is formatted
console.log(creature.name);
}
/*
R.I.P.
R.I.P.
Bull.
Swallow.
Kappa.
null
*/
Each creature is nested within another object, and since it's an array of objects (that contain the creature), you have to iterate over it with a for loop, to make use of it.
Your parsing of the JSON, then, was most likely correct, but the logic that came afterwards was not (at a total guess).
Your code seems perfectly valid. Try this jsfiddle.
var creatures = $.parseJSON(yourJSONString);
alert(creatures[0].creature.name); // alerts "R.I.P"
Do you need any specific clarifications?
I came across Datejs recently and found it very useful. However I could not figure out if there is a way to parse a string and extract only date part from it using the same.
For example, if there is a string >> "I will start exercise from next Monday."
Then it should parse the string, extract 'next monday' from it and convert it into date and give me the result.
How can it be implemented?
Thanks :)
You can write some RegEx for that. That would be the easiest way. 'next' will be a keyword in that case. A simple function can lookup the current weekday and return the date of the next monday. Should not that complicated.
Edit:
You can do something like this:
var pattern = /^([\w\W.]*)(next){1}([\sa-zA-Z]*)/;
while (result = pattern.exec(yourTextVariable) != null){
// read the data as you need from the result array
}
The Pattern above expecting a white space then the keyword next and will red the next word if it only has alpha-letters. (please note that the RegEx is untested and may need some refactoring to fit your needs. You may take a look at this page to do this: javascriptkit.com)
I am parsing a json string like so:
ring = JSON.parse(response);
Now, ring is an object but ring.stones is just a string when it should be an object as well.
If I call:
ring.stones = JSON.parse(ring.stones);
It is now the correct object.
I didn't know if this is correct behavior or if maybe I have an issue somewhere stopping it from parsing recursively? If it is supposed to parse recursively, are there any known issues that would prevent it?
Update
Here is the full response before parsing:
{"ring_id":"9","stone_count":"4","style_number":"style 4","syn10":"436.15","gen10":"489.39","syn14":"627.60","gen14":"680.85","available":"yes","type":"ring","engravings_count":"0","engravings_char_count":"0","engravings_band":"10","stones":"[{\"stone_id\":\"27\",\"ring_id\":\"9\",\"stone_shape\":\"round\",\"stone_x\":\"132.80\",\"stone_y\":\"114.50\",\"stone_width\":\"71.60\",\"stone_height\":\"71.60\",\"stone_rotation\":\"0.00\",\"stone_number\":\"1\",\"stone_mm_width\":\"5.00\",\"stone_mm_height\":\"5.00\"},{\"stone_id\":\"28\",\"ring_id\":\"9\",\"stone_shape\":\"round\",\"stone_x\":\"100.50\",\"stone_y\":\"166.20\",\"stone_width\":\"36.20\",\"stone_height\":\"36.60\",\"stone_rotation\":\"0.00\",\"stone_number\":\"2\",\"stone_mm_width\":\"2.50\",\"stone_mm_height\":\"2.50\"},{\"stone_id\":\"29\",\"ring_id\":\"9\",\"stone_shape\":\"round\",\"stone_x\":\"200.20\",\"stone_y\":\"105.10\",\"stone_width\":\"33.90\",\"stone_height\":\"33.90\",\"stone_rotation\":\"0.00\",\"stone_number\":\"3\",\"stone_mm_width\":\"2.50\",\"stone_mm_height\":\"2.50\"},{\"stone_id\":\"30\",\"ring_id\":\"9\",\"stone_shape\":\"round\",\"stone_x\":\"165.80\",\"stone_y\":\"82.50\",\"stone_width\":\"35.50\",\"stone_height\":\"33.90\",\"stone_rotation\":\"0.00\",\"stone_number\":\"4\",\"stone_mm_width\":\"2.50\",\"stone_mm_height\":\"2.50\"}]","images":"[{\"title\":\"white gold\",\"source\":\"Style4_4_W_M.png\"},{\"title\":\"yellow gold\",\"source\":\"Style4_4_Y_M.png\"}]"}
Update 2
Based on mikerobi's answer I was able to figure out what was happening:
Here is where I encoded it:
$row = $sth->fetch(PDO::FETCH_ASSOC);
$row['stones'] = getStones($ring_id);
$row['images'] = getRingVariations($ring_id);
return json_encode($row);
But the functions getStones and getRingVariations were returning json_encode'd strings. I needed to change them to return plain strings.
Your JSON structure is wrong, it is wrapping stones in quotes, turning it into a string.
Your JSON looks like:
{
stones: "[{\"stone_id":\"27\"},{\"stone_id\":\"27\"}]"
}
It should look like:
{
stones: [{"stone_id": 27},{"stone_id": 27}]
}
EDIT
It appears you are converting all values to string, including numbers, I updated my example to reflect this.
Also, I'm guessing by the output that you are writing your own code to serialize the JSON, I highly recommend using an existing library.
It is recursive, but your input string (response) is not in correct format. Get rid of those escape characters (\") and try again.