I have no idea what im doing wrong, but I have a JSON string with this:
jsonp443489({"content":"<!DOCTYPE html><html><head><title>Title</title></head><body><p>Hello World</p></body></html>"});
I need to parse this to be able to modify the content. Like, for example, id want to grab the <p>
's content.
Now, in jQuery if i do:
console.log($(json.content).html());
It returns Title
.
If i do:
console.log($('p',json.content));
It returns []
, or, an empty array.
Finally, if I do just: console.log($(json.content));
It returns [<title>Title</title>,<p>Hello World</p>]
Which is fine, but then I cant do .find()
or anything. Since I wont know what the HTML will be, i cant use $(json.content)[1]
.
Any ideas?
==UPDATE==
After hacking at this for a couple hours i decided to try XML. My example XML was:
<?xml version=\"1.0\" encoding=\"UTF-8\"?><doc><item>One</item><item>Two</item></doc>
It was giving me the same grief, then it hit me, its a JS object, not a string and jQuery is expecting a string. I went and did
$(JSON.stringify(json.content)).find('item')
And voila! I got an array of two items. I was pretty excited but then when I went and tried it with HTML again (using the JSONP return HTML snippet above):
console.log($(JSON.stringify(json.content)).find('p'));
I still get an empty array. It's driving me mad... Any more ideas?
JSON.stringify(json.content)
is unnecessary.json.content
is already a string (XML). If you pass a string toJSON.stringify
it just returns the same string. Maybe you should read up about about JavaScript objects and JSON first... – Felix Kling May 22 '11 at 8:14$(xml).find('item')
). It wont work. Convert it withJSON.stringify
then pass it in. It'll work. Ive been doing JS a long time and jQuery for going on 4 years. If the answer is so simple, and its just because I dont understand JS objects and JSON, give me a JSFiddle or JSBin link and just tell me how to do it rather than bashing my JS knowledge. – Oscar Godson May 22 '11 at 10:45JSON.stringify
will add quotation marks"
to the beginning and end of the string. So instead of<?xml ...
you get"<?xml ..."
. It nevertheless works without it: jsfiddle.net/MYNVj And I'm sorry if it seemed like that, but I did not intend to rant about your knowledge... – Felix Kling May 23 '11 at 0:17