How to get these Json values? - html

I'm hitting a wall with this code, where I should extract some Json code within an element attribute. Here is my attempt:
<div labels='[{label: "A", name: "dog"}, {label: "B", name: "cat"}]'></div>
var labels = $("div[labels]").attr("labels");
console.log(data[0].label);
That was my attempt to get just the first object label, but it gives me undefined. I also tried to parse data first but I get some token error in console. What am I exactly missing here? I just want to loop through the objects and for each of them get both label and name.

if your json array keys in qoutes that will work
like this :
[{"label": "A", "name": "dog"}, {"label": "B", "name": "cat"}]
var labels = $("div[labels]").attr("labels");
var data = $.parseJSON(labels);
console.log(data);
OR
var labels = $("div[labels]").attr("labels");
var data = JSON.parse(labels);
console.log(data);

Resolved.
The issue was that keys (label, name) were missing quotes, so it was not correctly parsed.
Resolved by placing
var labels = data_label.attr("labels").replace(/\\n/g, "\\\n").replace(/label/gi, "\"label\"").replace(/name/gi, "\"name\"");

HTML
<div data-labels='[{label: "A", name: "dog"}, {label: "B", name: "cat"}]'></div>
Javascript
jsonObj = eval(document.querySelector("div[data-labels]").dataset.labels)

Related

Cell google sheet as Json Source

I have a variable into Google Script for access to data through an API:
var ticket_data = { "header_items": [{ "label": "Cliente", "type": "text", "item_id": "2cba1baf-207c-4529-ab72-7d35363983fc","responses": {"text": "PRUEBA: ANALISIS FALLA 2"},},],"template_id":"template_5f9b4f399fe342ce94fefada009ee467"}
JSticket_data=JSON.stringify(ticket_data)
I can run UrlFetchApp.fetch() to access the API without error.
But if I store the variable data into a Google Sheet cell, and read the value like this:
var ticket_data=sheet.getRange('B1').getValue()
JSticket_data=JSON.stringify(ticket_data)
I get this value:
"{ \"header_items\": [{ \"label\": \"Cliente\", \"type\": \"text\", \"item_id\": \"2cba1baf-207c-4529-ab72-7d35363983fc\",\"responses\": {\"text\": \"PRUEBA: ANALISIS FALLA 2\"},},],\"template_id\":\"template_5f9b4f399fe342ce94fefada009ee467\"}"
UrlFetchApp.fetch() does not work correctly with that value.
I think that the problem is when I take the cell data by ticket_data=sheet.getRange('B1').getValue(), it take it as string, and then the JSON.stringify add a double quotes an then add the backslashes. I tried remove the backslash with replaceAll('\\','') but it did not work.
06-10-22
This is an Update after the answer 1 to add more information to my question.
Firs to all Thank you for your answer !! I'm sorry if I shoudn't write this update here. Please tell me where I must to do in the future
I'm sure I making something bad.
I have prepared the variable and parameters for UrlFetchApp as:
ticketJson = work_sheet.getRange('B1').getValue()
var params = {
method:"POST",
contentType:'application/json',
headers:{Authorization:"Bearer "+token},
payload: ticketJson,
muteHttpExceptions:true
};
var post_ticket = UrlFetchApp.fetch("https://api.website.io", params)
Logger.log(post_ticket)
the logger's answer is
Information {"statusCode":400,"error":"Bad Request","message":"Invalid request payload JSON format"}
but if I store the data into a variable and then excecute JSON.stringify() the results is OK.
var ticket_data = { "header_items": [{ "label": "Cliente", "type": "text", "item_id": "2cba1baf-207c-4529-ab72-7d35363983fc","responses": {"text": "PRUEBA: ANALISIS FALLA 2"},},],"template_id":"template_5f9b4f399fe342ce94fefada009ee467"}
JSticket_data=JSON.stringify(ticket_data) // if not excecute this, I get the same error that I tell before
I can't find where is the error Thanks again in advance
Omar
The first code snippet in the question gets a JavaScript object and converts it to a text string with JSON.stringify().
The second code snippet in the question gets a text string that does not need to be processed with JSON.stringify() in order to get a text string. It is a text string.
In other words, you can simply use this:
const ticketJson = sheet.getRange('B1').getValue();
...and use ticketJson as is in UrlFetchApp.fetch().

Reading json file in node.js

This must be something really silly. After spending the last few hours, I am here for help.
I have a users.json file
{
"Test_Session": {
"test_SessionID": [
{
"$": {
"id": "1"
},
"test_type": [
"1"
],
"Test_IDtest": [
"1"
],
"DataURL": [
"data1"
]
}
]
}
}
I try to read DataURL by
var jsonData = require('./users.json');
var test = JSON.stringify(jsonData)
console.log(test.Test_Session.test_SessionID.DataURL);
In console, I get "Can't read property test_SessionID of undefined".
What's going on?
Your main issue is that test_SessionID is an array, so when you try to access DataUrl, it will be undefined. You need to select the index of the test_SessionID object you want to read from. Try this:
console.log(test.Test_Session.test_SessionID[0].DataURL);
Also, you don't need to JSON.stringify anything, Node automatically reads the file in as JSON, so just doing
var jsonData = require('./users.json');
console.log(jsonData.Test_Session.test_SessionID[0].DataURL);
should work fine.
Node is already interpreting the JSON, try the following:
var test = require('./users.json');
console.log(test.Test_Session.test_SessionID[0].DataURL);

Writing to Firebase from GAS returns error

I am trying to write to Firebase from Google Apps Script.
I try this:
var act="https://SampleChat.firebaseIO-demo.com/users/fred/name.json";
UrlFetchApp.fetch(act,{"method":"post","payload":"test"});
and I get this error:
Request failed for https://SampleChat.firebaseIO-demo.com/users/fred/name.json
returned code 400. Truncated server response:
{ "error" : "Invalid data; couldn't parse JSON object, array, or value.
Perhaps you're using invalid characters in your key names." }...
Question
How do I write to Firebase from GAS? (What am I doing wrong?)
Answer
You must stringify the payload object.
Here is a question and answer example.
I tested it and it does work.
Example
function putToFire() {
var payload = '{ "first": "Foo", "last": "Bar" }';
var options = {
"method": "put",
"payload": payload
};
UrlFetchApp.fetch(
"https://SampleChat.firebaseIO-demo.com/users/fred/name.json",
options
);
}
The Key Trick
Notice the single quotes ' around the payload object?
In the following line:
var payload = '{ "first": "Foo", "last": "Bar" }';
That counterintuitive syntax seems to be the trick to making this work. ;-)
Alternative Syntax for Variable Payloads
If your payload is a variable, you can use JSON.stringify():
var payload=JSON.stringify({"first":"Foo","last":"Bar"});

adding json element in json file

I have a json file in my android local device, im able to read and edit the json file and store json data in it.
But the problem is arising when i want to insert new element in the json file. Im able to change the value of existing variables.
the json file data is:
var data = {items:
{id: "1", name: "Snatch", type: "crime"}
};
i want to add one more element to it so that json file will look like
var data = {items: [
{id: "1", name: "Snatch", type: "crime"},
{id: "7", name: "Douglas Adams", type: "comedy"}
};
i tried with
data.items.push{id: "7", name: "Douglas Adams", type: "comedy"}
but its not working.
im creating android app using phonegap framework with telerik IDE.
Try
data.items.push(
{id: "7", name: "Douglas Adams", type: "comedy"}
);
You are missing ()
Your first file example is missing []
Check out this links to know more about json addition and removal
Link 1 , Link 2

How to return a Date value from JSON to Google Visualization API

is there a way to retrieve date value from JSON in Google Visualization API?
Here is the snipplet for playground please copy the code below into it
When you run the code you won't have anything in result. you should remove the quotes from the date value I marked with comment in order to retrieve result.
function drawVisualization() {
var JSONObject = {
cols:
[
{id: 'header1', label: 'Header1', type: 'string'},
{id: 'header2', label: 'Header2', type: 'date'}
],
rows:
[
{
c:
[
{v: 'Value1'},
{v: "new Date(2010, 3, 28)"} // <= This is the format I receive from WebService
]
},
{
c:
[
{v: 'Value2'},
{v: new Date(2010, 3, 28)} // <=This is the format Google API accepts
]
}
]
};
var data = new google.visualization.DataTable(JSONObject, 0.5);
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {'allowHtml': true});
}
I just ran into this problem myself, so I thought I'd paste the answer from the google api documentation, located here http://code.google.com/apis/chart/interactive/docs/dev/implementing_data_source.html#jsondatatable
"JSON does not support JavaScript Date values (for example, "new Date(2008,1,28,0,31,26)"; the API implementation does. However, the API does now support a custom valid JSON representation of dates as a string in the following format: Date(year, month, day[,hour, minute, second[, millisecond]]) where everything after day is optional, and months are zero-based."
I was running into same problem and above solution did not work. After searching for hours I found following post and the solution in there worked.
https://groups.google.com/forum/#!msg/google-visualization-api/SCDuNjuo7xo/ofAOTVbZg7YJ
Do not include "new" in the json string so it will be just:
v:"Date(2009, 9, 28)"
I suppose that the quote is not at the correct place in your snippet "new Date(2010, 3, 28")
Write instead "new Date(2010, 3, 28)"
Json format does not accept javascript object so the server return a string.
JSON knows only numbers, boolean constants, string, null, vector and 'object' (much more a dictionnary).
I suppose that you have to perform an eval() of the returned string (do not forget to check inputs).
Another alternative is to use a Regex to extract the fields something like /new Date\((\d+),(\d+),(\d+)\)/ will work.