May seem silly for most of you but I need to parse a JSON string as an array using JavaScript.I'm completely new to JSON and JavaScript and trying to make sense since last two days.
I need to read this JSON as an array and parse it using Javascript. In this example the JSON returned is single element, however in specific cases it returns multiple results(array)
[
{
"CauseAndEffect_Status": "InProgress",
"CurrentPhase": "Planning",
"cityCountry": "Walker French Southern Territories",
"location": "bangalore",
"siteAddress": "Sharon Street Canda Avenue",
"siteName": "DAISU",
"status": "95%",
"zipCode": 12940
}
]
Although the above JSON is an array object,I get the following error when I try to parse this JSON
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data of Jquery-2.1.4.min.js
If it comes from the server as a string, you can use
var myArray= JSON.parse(myJsonString);
and you you'll have an array of objects myArray which you can cicle with a simple for loop
Code For Parsing Json in Javascript . See the Js Fiddle below
var str ='{"CauseAndEffect_Status": "InProgress","CurrentPhase": "Planning", "cityCountry": "Walker French Southern Territories","location": "bangalore","siteAddress": "Sharon Street Canda Avenue","siteName": "DAISU","status": "95%","zipCode": 12940}';
var json = JSON.parse(str);
console.log(json);
$.each( json, function( ky, val ) {
console.log('ky => '+ky);//will output: name, firstname, societe
console.log('val => '+val);//will output: name1, fname1, soc1
});
CHECK THE BROWSER CONSOLE TO SEE RESULT
Related
I have the following multidimensional javascript array:
My js array
and I want to parse it and return some values from it (name and url)
but when cleaning it up a bit $jsonData = str_replace('var stations = ','' ,$jsonDataUrl); and trying to parse it as json with json_decode($jsongoeshere), the parser returned error 4 even if this URL had told me
that The JSON input is valid in JavaScript.
So now I am a bit lost on how to parse it.
quoted object property name expected is your error.
Your JSON string is not valid, object property names must be quoted.
This
{
"aland": [
{
name: "Ålands Radio",
logo: "stations/images-europe/aland/Ålands Radio.png",
url: "http://194.110.182.131:8000/stream.ogg"
},
...
Should be
{
"aland": [
{
"name": "Ålands Radio",
"logo": "stations/images-europe/aland/Ålands Radio.png",
"url": "http://194.110.182.131:8000/stream.ogg"
},
...
These JSON validators give you the correct error.
https://jsonlint.com/ & https://jsonformatter.curiousconcept.com/
Also, what #JJAulde said is true.
You have a semicolon at the end of your JSON string that will cause the parse to fail. You need to rtrim or str_replace it like you did with var stations =
This may be a very simple question but I really can't seem to make it work.
I have several JSON lines and a notes array.
Using notes.push(JSONline) I am saving one JSON line per array position, I assume, so in the following manner:
//notes[1]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}
//notes[2]
{"id":"27","valuee":"134","datee":"2016-04-05T15:15:47.238+0100","id2":53}
//notes[3]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":52}
Here is my problem: I want to print one specific attribute, for example id from one specific JSON line in the array. How can I do this?
When I do console.log(notes) it prints all the JSON lines just as expected. But if I do console.log(notes[1]) it prints the first character of the JSON line in that position, not the whole line.
Similarly console.log(notes[1].id) does not print the id from the first JSON line, in fact it prints 'undefined'.
What am I doing wrong?
Thank you so much.
I'd recommend that you parse all the json when you are pushing to notes, like:
notes.push(JSON.parse(JSONLine))
If you are somehow attached to having json strings in an array instead of objects, which I wouldn't recommend, you could always just parse once you have the jsonLine id
JSON.parse(notes[id]).id
Basically, you want to use JSON.parse for either solution and I'd strongly recommend converting them to objects once at the beginning.
You need to remember that JSON is the string representation of a JS object. JS strings have similar index accessor methods to arrays which is why you can write console.log(notes[0]) and get back the first letter.
JavaScript doesn't allow you to access the string using object notation, however, so console.log(notes[0].id) will not work and the reason you get undefined.
To access the data in the string using this method you need to parse the string to an object first.
var notes = ['{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}'];
var note0 = JSON.parse(notes[0]);
var id = note0.id;
DEMO
This leaves the question of why you have an array of JSON strings. While it's not weird or unusual, it might not be the most optimum solution. Instead you could build an array of objects and then stringify the whole data structure to keep it manageable.
var obj0 = {
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
id2: 51
};
var obj1 = {
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
var arr = [obj0, obj1];
var json = JSON.stringify(arr);
OUTPUT
[
{
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
"id2": 51
},
{
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
]
You can then parse the JSON back to an array and access it like before:
var notes = JSON.parse(json);
notes[0].id // 26
That's because you have {"id": "value"... as a string in your key value pairs. "id" is a string so you can't reference it like a property. 1. use
var notes = JSON.parse(notes);
as mentioned in the comments by The alpha
or remove the quotes try
{id:"26", ...}
that's why notes[i].id is returning undefined
I was getting list in array form. So at first place i converted array list to string-
var myJsonString = JSON.stringify(result);
myJsonString="[{"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
},
{"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
}]"
But again i need to convert myJsonString to Json format, What i need to do? I mean i need to replace 1st" and last ", I guess
You need to call parse now.
JSON.parse(myJsonString)
First, if you ever find yourself building a JSON string by concatenating strings, know that this is probably the wrong approach.
I don't really understand how the first line of your code relates to the second, in that you are not doing anything with JSON-encoded string output from result, but instead just overwriting this on the following line.
So, I am going to limit my answer to show how you could better form JSON from an object/array definition like you have. That might look like this:
// build data structure first
// in this example we are using javascript array and object literal notation.
var objArray = [
{
"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
},{
"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
}
];
// now that your data structure is built, encoded it to JSON
var JsonString = JSON.stringify(objArray);
Now if you want to work with JSON-encoded data, You just do the opposite:
var newObjArray = JSON.parse(JsonString);
These are really the only two commands you should ever use in javascript when encoding/decoding JSON. You should not try to manually build or modify JSON strings, unless you have a very specific reason to do so.
I have a local JSON file which I converted into a JS object by adding var data = ... in front of that:
var data = {
"people": [
{
"name": "Martin",
"surname": "Smith"
},
{
"name": "Jack",
"surname": "Smith"
}
]
}
I load it with: <script src="data.json" type="text/javascript"> and try to parse it with:
var h = JSON.parse(data);
I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
When you put var data = { in front of it, it stops being JSON and becomes JavaScript. (So you shouldn't give it a .json file extension and that will encourage servers to tell browsers that it is JSON and not JS).
In this case, it is a JavaScript program that assigns an object to a variable.
JSON.parse takes a string containing JSON and converts it into a JavaScript object (or array or other data type).
Don't parse it. It is already parsed by the JavaScript compiler.
Here MZN JSON.parse() you can see what JSON.parse() should be used for. It is used on a String that contains a JSON object, and this method would parse it into the format that your data variable is already in. Since your data variable is already in JSON format, your variable is ready to use and you do not need the JSON.parse() method.
BackGround : I am trying to parse this simple json response in my SenchaTouch Application.
json response:
{
"Australia":
[
{
"Currency": "AustralianDollar",
}
],
"INDIA":
[
{
"Currency": "INR"
}
],
"USA":
[
{
"Currency": "USD"
}
]
}
I want to fetch country's currency based on the Country name.
I am trying to fetch the currency value as below.
var country = text.Australia.name;
console.log('Country name is'+country);
but it gives me error. Can any one please explain on how to parse give country name as input and fetch the currency?
Thank you,
Gendaful
If text is the JSON string you can do this:
var obj = JSON.parse(text);
var australia = obj.Australia;
var aussie_currency = australia[0].Currency;
Note that the odd nesting of the object containing Currency inside of an array causes the need for the array index reference [0].
In Sencha Touch you should use
var object = Ext.decode(text);
to convert a json string into an Object.
Then, in your case, since "Australia" in not an object but an array, you need to get the first element currency by
object.Australia[0].Currency;
The simplest way to do it is:
var obj = eval("(" + text+ ')');
Check out json.org for better/safer ways to do it.
Working example here.
Check out this compatibility chart for using JSON.parse(text);.
Best way to do this if by using JSON.parse(). All browsers does not support this but you can get fallback by using Douglas Crockford implementations at https://github.com/douglascrockford/JSON-js
You can use jQuery's $.parseJSON()
After that you can use:
var text = $.parseJSON(jsonString);
var currency = text.Australia[0].Currency;
Being the jsonString, the one you obtain via JSON.
Hope this helps!