2

I have json message in this format

{"id":21,"image":"binary64image","pdate":"2014-01-27"},
{"id":22,"image":"binary64image","pdate":"2014-01-27"},
{"id":21,"image":"binary64image","pdate":"2014-01-27"}

and I want to convert this into javascript array, I have tried

        var txt = '{ "potholes" : [' + data + ']}';
        var jsonObj = eval("(" + txt + ")");            
        alert(jsonObj.potholes[1].id);

and

        var potholes = JSON.parse(data);
        alert(potholes[1].id);

neither worked. The data is there as it is in a success to an ajax call which returns json object.

4
  • 1
    What is console.log(data)? An array? A string? Commented Jan 27, 2014 at 11:56
  • just in case you've not... have you tried: JSON.stringify(jsonObj) ? Commented Jan 27, 2014 at 11:57
  • Alert(data) overloads the messagebox on my android phone, but I have test from server from my webservice which returns application/json as above Commented Jan 27, 2014 at 12:00
  • The JSON is broken (unless you did not paste it completely). Commented Jan 27, 2014 at 12:05

3 Answers 3

1

Your example work great!

simple data should be a string

data = '{id: ....'

http://jsfiddle.net/VSDC7/1/

Sign up to request clarification or add additional context in comments.

1 Comment

Yes it was working although I had square brackets round my data, which caused it to fail as the string already had these. I would have fixed this a lot sooner but I do not have a console as working on phonegap
1

You should convert your input data to an array (fiddle):

var input = '{"id":21,"image":"binary64image","pdate":"2014-01-27"},{"id":22,"image":"binary64image","pdate":"2014-01-27"},{"id":21,"image":"binary64image","pdate":"2014-01-27"}',
    inputArr = '[' + input + ']',
    arr = JSON.parse(inputArr);
for (var i in arr)
    console.log(arr[i].id);

Comments

1

You can convert your JSON response in JavaScript array like below :

var data = '{"id":21,"image":"binary64image","pdate":"2014-01-27"},{"id":22,"image":"binary64image","pdate":"2014-01-27"},{"id":21,"image":"binary64image","pdate":"2014-01-27"}';
var result = eval("["+data+"]");  //convert your response into JavaScript array

for(var i in result) // read your array value
    alert("id : "+result[i].id+" --> image : "+result[i].image+" --> pdate : "+result[i].pdate); 

Fiddel Example

1 Comment

eval is a bad way to parse json. You can read about it on mdn

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.