parse “application/x-www-form-urlencoded” response with javascript - javascript

How do you parse a x-www-form-urlencoded string with JavaScript?
I tried to parse to JSON and able to iterate the keys using Object.Keys()
my responseText = {
"response": {
"header": {
"error_code": 0
},
"body": {
"foo": "foobar",
"date": "2018-04-27"
}
}
}

Url encoded forms have the structure key=value&key2=value2&.......
The keys and values are encoded, for more info on url encoding: https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4
In case any value is an object with more keys and values inside it, the form will contain each of the keys inside said object as a description of their path relative to the root, using [].
Your example would look like:
response[header][error_code]=0&response[body][foo]=foobar&response[body][date]=2018-04-27
I think with this info you can probably figure it out, just keep in mind that the text is encoded, unlike in my example.

Related

JSON.parse giving only the last element as output

I am using JSON to carry information from NodeJS (server side) to my client side. When I try to parse the JSON in the client side, it outputs only the last element, in this case, 'name: "Sam"'. I want all the elements to be outputted.
I have tried using an array and a variable to be assigned the parsed data. I have also directly tried logging it to the console with: [console.log(JSON.parse(this.response));]. All three gave the same result.
The first console.log returns all the elements in JSON form. The second one returns only the last one. There are 3 elements in total.
I expect all the elements to be assigned to the variable.
request.open('GET', 'http://localhost:3000/listofvoted', true);
request.onload = function () {
console.log(this.response)
console.log(JSON.parse(this.response));
}
request.send();
The JSON I receive:
{
"name": "Bran",
"name": "Ram",
"name": "Sam"
}
Although JSON (which is just a notation) allows for duplicate key names, the guidance is that that they SHOULD be unique. If you want to use JSON to create a JavaScript Object, then you are constrained by the fact that a JavaScript Object cannot have duplicate keys. So although you have valid JSON, it cannot be represented by a JavaScript Object and therefore it will not survive a round trip of being parsed (JSON converted to a JavaScript Object) by JSON.parse and then converted back to JSON.
For your own convenience of working in JavaScript, you could consider changing the JSON representation of your information so that it can be represented as a JavaScript Object.
Here are some alternative ways of representing what you have that may work:
Use an array of discrete objects:
[
{ "name": "Bran" },
{ "name": "Ram" },
{ "name": "Sam }"
]
Use an array of names:
{
"names": [ "Bran", "Ram", "Sam" ]
}
As a final, heavy-handed approach, you don't have to convert your JSON to a JavaScript object. You can parse it using a parser that allows you to provide your own handlers for the syntactic elements that occur in the JSON string and you can handle the duplicate keys in whatever way you wish. May I suggest the clarinet library for doing so.
See also, How to get the JSON with duplicate keys completely in javascript

parsing multidimensional javascript json array with php

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 =

How to access an attribute from a JSON line saved in a position from an array?

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

javascript (no jquery) - load a local json file

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.

How to use the json?

I have called an api using href from the html form and it in response gives json as output.
consider this as the json the api gives
{
"entry":
{
"id": "1",
"name": "SA"
}
}
I want the values of the id and name.
How can i get the values specifically and store those values to a variable.
Also i got to do this in the html form with javascript.
I want the values of the city_id and city_name. How can i get the
values specifically and store those values to a variable
Use JSON.parse to convert it to JS object and get your values:
var obj = JSON.parse(yourJSON);
var city_id = obj['entry']['city_id'];
var city_name = obj['entry']['city_name'];
Docs:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse
var a;
eval('a={"entry":{"#collection_url":"http://api.storageroomapp.com/accounts/4fe004c598f46026cc000002/collections/4fe0063798f4602e2c000016","#created_at": "2012-06-21T09:12:40Z","#trash": false,"#type": "City","#updated_at": "2012-06-21T09:12:40Z","#url":"http://api.storageroomapp.com/accounts/4fe004c598f46026cc000002/collections/4fe0063798f460e2c000016/entries/4fe2e58898f4604757000006","#version": 1,"city_id": "City_001","city_name": "London"}}');
in other words
eval ('a={/*response object*/}')
now you have (a) as object that contains your data you can access them whether like object notation (a.entry) or as an array (a['entry'])
you can also use json parse but its not compatible with all browsers
Either the eval() function or the JSON parser will allow you to create an object from the JSON and then access the fields normally. The JSON parser is a little more secure, as explained in this tutorial:
http://www.w3schools.com/json/json_eval.asp

Categories

Resources