How to passing an Object from HTML to JavaScript - javascript

How to convert html data attribute into JavaScript Object?
I try to use JSON.parse() but it got some error
There is result of my String Data
{
_id: 5f71ea3362749a305427a012,
name: 'House With Beauty Backyard',
__v: 0
}
When i use JSON.parse() it return error
VM5246:2 Uncaught SyntaxError: Unexpected token _ in JSON at position 4
My EJS Code
<i class="fas fa-edit"></i>
My JS Code
<script>
$('#dataTable .btn-update').on('click', function () {
let dataString = $(this).data('category');
console.log(dataString);
let dataJson = JSON.parse(dataString);
console.log(dataJson);
$('#update-modal').modal('show');
})
</script>

Use JSON.stringify. Try this code:
let dataJson = JSON.parse(JSON.stringify(dataString));
console.log(dataJson);

JSON requires quotes ("") for keys and string values.
This would be your "String Data" with valid form:
{
"_id": "5f71ea3362749a305427a012",
"name": "House With Beauty Backyard",
"__v": 0
}
The parsing error will disappear, if you change your data format to valid JSON.(RFC 8259)
Here you can find out more about JSON:
https://tools.ietf.org/pdf/rfc8259.pdf

Related

get error when json_decode string from ajax post

I try send string to controller, the string is json format, when send to controller, i get error and can't decode my json string in that controller. I try to encode first in my controller, but still get error. And the error is
"json_decode() expects parameter 1 to be string, array given",
exception: "ErrorException",
here in my json string
"{ "data" :
[{
"id": "TNI01",
"jenis_bayar": "TUNAI",
"no_kartu": "kosong",
"nominal": "10000",
"seq": "1"
} ,
{
"id": "DEB01",
"jenis_bayar": "DEBIT BCA",
"no_kartu": "786382432432",
"nominal": "20000",
"seq": "2"
}]
}"
here the controller
public function ArrayPostToTablePembayaran(Request $request)
{
$data = json_decode($request->datajson, true);
foreach ($data->data as $datas)
{
$id = $datas->id;
$jenisbayar = $datas->jenis_bayar;
$nokartu = "";
if($datas->no_kartu == "kosong")
{
$nokartu ="";
}
$nominal = $datas->nominal;
$seq = $data->seq;
$this->PosToTablePembayaran1($id , $jenisbayar , $nokartu , $nominal , $seq);
}
}
and here the ajax script for parse json string to controller
function PembayaranKeDatabase1(arraystring)
{
$.ajax(
{
type : "POST",
url : "{{ url('/trx_bayar') }}",
data : { datajson : JSON.parse(arraydata) } ,
dataType: "json",
success: function(data){
},
error: function() {
}
});
}
thanks before
The main issue in your code that you try to decode json twice: in client js code and on server.
Let's inspect what you do:
JS function PembayaranKeDatabase1(arraystring) has an argument of type string, I presume. I also presume that arraystring is a JSON-string. So, you decode JSON-string to object with
JSON.parse(arraydata)
// btw shouldn't it be
//JSON.parse(arraystring)
So, here you send some plain object to server, not json.
Next, on server you try to decode again. But you receive an array in $request->datajson, as json is already decoded on client-side.
So, you can choose between two options:
Remove JSON.parse:
data : { datajson : arraydata },
and use json_decode on server.
Remove json_decode($request->datajson, true) on server. Iterate over your data as
// as $request->datajson is an array
foreach ($request->datajson['data'] as $datas) {
// use [] notation as you work with array, not object
echo $datas['id'];
}

Can't access JSON Object no matter what i'm trying

So i have this JSON Structure, which i want to access:
data { payload: "{"state":{"reported":{"measuredata":{…
JSON.parse doesnt work, neither does JSON.stringify.
i only can access payload, if i go any further, i receive error or undefined:
data.payload // works
data.payload["state"] //undefined
data.payload.state // undefined
data.payload[0].state // undefined
data.payload[0]["state"] // undefined
what am i doing wrong?
the thing that i can see is that you have a bad format on your json data { payload: "{"state":{"reported":{"measuredata":{…
it hspuld be witouth the double quote that be after the word payload payload: "{"state"
you have to have something like this
payload: {"state"
You just need to use JSON.parse for payload json string value.
JSON.parse(data.payload).state;
Sample code for parsing.
var data = {
"logged_in":true,
"town":"Dublin",
"state":"Ohio",
"country":"USA",
"products":
{
"pic_id":"1500",
"description":"Picture of a computer",
"localion":"img.cloudimages.us/2012/06/02/computer.jpg",
"type":"jpg",
"childrenimages":
{
"pic_id":"15011",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/mycpu.png",
"type":"png"
}
}
};
var data1 = JSON.stringify(data);
var data_final = JSON.parse(data1);
console.log(data_final.products.pic_id);

Object to JSON angularjs

I have this method
function submit() {
var JSONObject = {
"name":$rootScope.name,
"surname":$rootScope.surname,
"email":$rootScope.email,
"review":$rootScope.review
};
debugger;
var Results = UniversalService.PostReview(JSONObject);
}
which I want to post to database later and I get error: SyntaxError: Unexpected token o in JSON at position 0
As I understood I get incorrect JSON format as my console.log input shows :
Object {name: "hh", surname: "hh", email: "kal#gmail.com", review: "fre"}
Instead it should show : "name": "hh" info like this right? How do I change that?

Ruby - parsing JSON coming via URL

I'm sending a JSON object to ruby with javascript. But I cannot parse it in there. I tried following stuff but no luck. Also I've been searching around for while now, but I couldn't find anything helpful.
Note that I'm very new ruby.
My trials:
def initialize(game_conf_json)
parsed_conf = JSON.parse(conf_json)
#param1 = parsed_conf['name'][0]
#param2 = parsed_conf['surname'][0]
=begin
I also tried this:
#param1 = parsed_conf['name']
#param2 = parsed_conf['surname']
But no matter what other things I try, I'm getting the following error:
"21:in `[]': can't convert String into Integer (TypeError)"
OR
"can't convert Array into String (TypeError), "
=end
File.open("some_direc/conf.json", "w") do |f|
f.write(game_conf_json)
end
end
I create the json in javascript like this:
var json_of_form_vars = {};
json_of_form_vars.name = name_val;
json_of_form_vars.surname = surname_val;
And send it this way:
$.ajax({
url: "../fundament/dispatch.rb/",
type: "post",
dataType: "json",
data: "conf="+json_of_form_vars,
.....
How can I solve this problem? Is there any proper tutorial for this of problem?
UPDATE1 (After suggestions):
I used JSON.stringify and then passed the object to ruby. And then I finally able to print the object in ruby. It's listed below:
{"name": "METIN", "surname": "EMENULLAHI"}
The method .class claims that it is an array. But I cannot access data with classical ways, like:
array['name']
the error is:
can't convert String into Integer
And when I try to pass it to the JSON.parse in ruby, it gives me the following error:
can't convert Array into String
So I used JSON.parse(conf_array.to_json), but again when accessing the data it gives the same error like arrays:
can't convert String into Integer
What should be done now?
UPDATE2
Here is my cgi handler which passes the URL parameters to appropriate places:
cgi_req = CGI::new
puts cgi_req.header
params_from_request = cgi_req.params
logger.error "#{params_from_request}"
action_todo = params_from_request['action'][0].chomp
base = Base.new
if action_todo.eql?('create')
conf_json = params_from_request['conf']
# This line prints the json like this: {"name": "SOME_NAME", "surname": "SOME_SURNAME"}
logger.error "#{conf_json}"
base.create_ident(conf_json)
end
And in Base class:
def create_ident(conf_json)
require 'src/IdentityCreation'
iden_create = IdentityCreation.new(conf_json)
end
IdentityCreation's constructor is listed above.
UPDATE3:
Ok, I now get at least something out of the array. But when I access a key, it displays the key itself:
parsed_conf = JSON.parse(conf_json.to_json)
#param1 = parsed_conf[0]['name']
#param2 = parsed_conf[0]['surname']
# At this point when I print the #param1, it gives me "name"(the key), not "SOME_NAME"(the value).
Here an example of parsing a JSON string. If you still have problems, publish the generated JSON so that we can try it.
require 'json'
require 'ap'
string = %{
{"configurations" : [
{ "drinks" : [
{"menus" : [
{ "hot" : [
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 4},
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 6}
] },
{ "cold" : [
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 4},
{"id":15,"unit":"0.33", "price":"1", "currency":"Euro", "position": 6}
] },
{ "terminals" : { "id" : 4, "id": 6, "id": 7 } },
{ "keys" : { "debit" : "on", "credit": "off" } }
] }
] } ] }
}
hash = JSON.parse(string)
ap hash
gives
{
"configurations" => [
[0] {
"drinks" => [
[0] {
"menus" => [
[0] {
"hot" => [
[0] {
"id" => 15,
"unit" => "0.33",
"price" => "1",
"currency" => "Euro",
"position" => 4
},
etc..
At the moment you're not actually posting json. You're attemping to post json wrapped inside form encoded parameters. In addition, when you do
"conf=" + json_of_form_vars
javascript will convert json_of_form_vars to a string for you but that conversion isn't the same as dumping to JSON. Javascript default string conversions are pretty useless for objects, so you'll need to use JSON.stringify to get actual json.
Since you're composing the body as a string literal you'll also need to escape any special characters that aren't allowed (or have special meaning) in this context. It's usually easier to let jquery do the heavy lifting, with something like
$.ajax({
url: "../fundament/dispatch.rb/",
type: "post",
dataType: "json",
data: {conf: JSON.stringify(json_of_form_vars)}
I solved it finally. Using all the suggestions made under this post and also my irb experiences with hashes, arrays, json and etc.
So instead of converting my object (conf_json) to json (with to_json), I passed it to JSON.parse as a string like below:
parsed_conf = JSON.parse(%{#{conf_json}})
It seems kind of weird to me, because when try to pass it to function like below, I got the error of can't convert Array into String.
parsed_conf = JSON.parse(conf_json)
But it is working like a charm right now.

Error parsing JSON from Tag-Content

I'm passing an json object to my js file:
<script type="text/javascript" src="../js/main.js">
{ lang: 'de' }
</script>
Trying to get the json object in main.js:
var scriptContent = $('script').filter(function () { return this.src.match(/js\/main\.js/g); }).html(),
params = $.parseJSON( scriptContent.replace(/"/g, '"') );
But this results in the following error: JSON.parse: expected property name or '}'
As you can see I already tried replacing " by "
I tried { lang: "de" } instead of { lang: 'de' }
How to get this working?
Properties in JSON should be surrounded by quotes, like this:
{
"lang": "de"
}
Also, to test if a JSON piece is valid you should use http://jsonlint.com/
Your snippet is incorrect JSON. Property keys have to be quoted too.
To quickly produce valid JSON (for testing purposes?), use JSON.stringify( some_object ), eg:
JSON.stringify({ lang: "de" });
>>> {"lang":"de"}
Use JsonLint to validate your JSON object
{
"lang": "de"
}
add also :
scriptContent = scriptContent.replace(/\n/g, '');
to remove brak-lines

Categories