How to parse large nested json objects? - javascript

PasteBin JSON
I would like to get this as Object it says jsonlint is valid but parsing is not anyone help would appreciate
"Data":[{...},{...},] // structure build like this
when i try
JSON.parse(jsonparamter) <-- Uncaught SyntaxError: Unexpected token A in JSON at position 71
at JSON.parse (<anonymous>)
at <anonymous>:1:6

There are multiple levels of JSON encoded data so you will have to create a loop to decode the elements deeper in the JSON nest. Use the below code to see an example of accessing Data.Adress.Value in this dictionary
// set up urls and headers for making HTTP req
corsurl = 'https://cors-anywhere.herokuapp.com/'
jsonurl = 'https://pastebin.com/raw/vuecweML'
headerNames = ['Content-Type','Accept']
headerValues = [ 'application/json', 'application/json']
// Modular get request function that I use
function getRequest (baseRestURL, APIPath, headerNames, headerValues, callback) {
var completeRestURL = baseRestURL + APIPath
console.log('REST API URL: ' + completeRestURL)
var method = 'GET'
var url = completeRestURL
var async = true
var request2 = new XMLHttpRequest()
request2.onload = function () {
console.log('ONLOAD')
var status = request2.status // HTTP response status, e.g., 200 for "200 OK"
console.log(status)
console.log(request2.responseText)
var response = request2.responseText
return callback(response)
}
request2.open(method, url, async)
for (var i in headerNames) {
request2.setRequestHeader(headerNames[i], headerValues[i])
}
request2.send(null)
}
// Our code of interest
getRequest(corsurl, jsonurl, headerNames, headerValues, response => {
parsed = JSON.parse(response).Data //parse our data the first time, and get the data attribute from dictionary
objects = JSON.parse(parsed) // parse a second time ( as data is JSON encoded twice )
selection = JSON.parse(objects[0].Address)[0].Value // parse a third time and select an attribute
document.getElementById('result').innerHTML = selection // Add it to our html to display
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id='result'> Loading </div>

Related

Unexpected token 'o', "[object Obj"... is not a valid JSON

I have written a function in PHP which takes product information and user's desired calories information from a database and puts all of the information in an array. Afterwards it's encoded in JSON. Then the PHP file is used in a Javascript .html file where it should take the information I just said about from the PHP file and outputs the linear program results. The problem is that the .html file with Javascript in it returns an error in the console and a white page (screenshot).
The PHP file output is shown in the screenshot. I took the output and pasted it in a JSON validator, which shows that it's valid, so I don't see the issue here.
Any suggestions?
PHP(part):
// Add the product data to the products array
$products[] = [
'name' => $productRow['product_name'],
'price' => $price,
'calories' => $energyRow['energy_value'],
'UserCalories' => $userCaloriesRow['calories'],
];
}
// Output the products array as a JSON string
header('Content-Type: application/json');
echo json_encode($products, JSON_UNESCAPED_UNICODE);
$mysql->close();
return $products;
}
fetchProductsFromDatabase();
?>
Javascript:
<script src="https://unpkg.com/javascript-lp-solver#0.4.24/prod/solver.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Initialize the products and calories arrays
var products = [];
var calories = 0;
// Make an AJAX request to the PHP script that fetches the products and user's desired calories from the database
$.ajax({
url: 'fetchProductsFromDatabase.php',
success: function(response) {
// The response is a JSON object, so we need to parse it to get the products array and user's desired calories
var data = JSON.parse(response);
products = data.products;
// Set up the linear programming problem
var lp = new LinearProgramming(0, LinearProgramming.MAXIMIZE);
// Set up the constraints
var caloriesConstraint = {};
for (var i = 0; i < products.length; i++) {
caloriesConstraint[i] = products[i]['calories'];
}
lp.addConstraint(caloriesConstraint, LinearProgramming.EQUAL, calories);
// Set up the objective function
var priceObjective = {};
for (var i = 0; i < products.length; i++) {
priceObjective[i] = products[i]['price'];
}
lp.setObjective(priceObjective);
// Solve the linear program
var result = lp.solve();
// Print the results
for (var i = 0; i < products.length; i++) {
console.log(products[i]['name'] + ': ' + result[i]);
}
console.log('Total cost: ' + lp.getObjectiveValue());
},
error: function(jqXHR, textStatus, errorThrown) {
// There was an error with the request
console.log(jqXHR.responseText); // Output the response from the server
console.log(textStatus); // Output the error type
console.log(errorThrown); // Output the exception object, if available
}
});
</script>
The parameter passed to the success callback in jQuery's ajax method has already been parsed. It is not the string of JSON returned by the PHP, it is the result of reading that string of JSON into an ordinary JS object.
In short, JSON.parse has already been run before it gets to your code.
So instead of this:
success: function(response) {
// The response is a JSON object, so we need to parse it to get the products array and user's desired calories
var data = JSON.parse(response);
products = data.products;
// ...
You just want this:
success: function(data) {
// The response data is an object, from which we can get the products array and user's desired calories
products = data.products;
// ...
The reason you get the error you do is that JSON.parse expects a string (a string of JSON data), but you're passing it an object (the one jQuery has passed you). JavaScript "helpfully" turns the object into the string '[Object object]', and passes it to JSON.parse.
you need to stringify the JSON before parsing, something like:
JSON.parse(JSON.stringify(response));
Best regards,

posting json parameter to api use post method Swift 3

I need to pass the following json to this function so Shopify Api can understand the submission. I am unable to create the correct variable format and pass it to server.Shopify API is expecting the following json to be passed via POST
Replace REQUEST_URL with your API URL
Replace JSON_STRING with your actual json string
var request = URLRequest(url: URL(string: "REQUEST_URL")!)
request.httpMethod = "POST"
let postString = "JSON_STRING"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
convert your object into dictionary and then serialize it by
do{
let data = try JSONSerialization.data(withJSONObject: dict, options: [])
postString = String.init(data: data, encoding: String.Encoding.utf8)!
}catch{
print(error)
}

Convert JSON response to Google Sheet ( Google Apps Script)

I have been trying to figure out to insert the JSON response into google Sheet in Google Apps Script with below code but for some reason I am getting error while trying to run.
please see screenshot and below code.
function myFunction() {
var key_67 = 'YYYYYYYYYYYYYYYYYY';
var ss_67 = SpreadsheetApp.openById(key_67);
var sheet_67 = ss_67.getActiveSheet();
sheet_67.getRange('A1:AZ10000').clearContent();
var url = 'https://creator.zoho.com/api/json/arfater/view/Leads_Report?authtoken=XXXXXXXXXXXXXXXXXXXX&scope=creatorapi&zc_ownername=ipekuet';
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
var stats=[]; //create empty array to hold data points
//The following lines push the parsed json into empty stats array
stats.push(data.Yearly_Sales); //temp
stats.push(data.Email); //dewPoint
stats.push(data.Phone); //visibility
//append the stats array to the active sheet
sheet_67.appendRow(stats)
}
So your JSON response based on postman app is
var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test#zoho.com","Phone":"123-032-03323","P‌otentially":50,"Stat‌e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]};
When I use that response as is:
function JsonResponse(){
var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test#zoho.com","Phone":"123-032-03323","P‌​otentially":50,"Stat‌​e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]} '
var data = JSON.parse(json);
Logger.log(data);
}
I get the same error as you:
SyntaxError: Unexpected token: v
Which leads me to believe your response from API has this term var zohoipekuetview65 (Not really sure as to why? a bug perhaps)
The below code splits the response string to give you the JSON response only
function trialParse(){
var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test#zoho.com","Phone":"123-032-03323","P‌​otentially":50,"Stat‌​e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]} '
Logger.log(JsonResponse(json))
}
function JsonResponse(response){
Logger.log(response)
var json = response.split("=")[1]
var data = JSON.parse(json);
Logger.log(data);
return data
}
Just call the above function in your code using var data = JsonResponse(json)
Final Note: As mentioned by Jordan Rhea you can use Logger.log(json) to output the response to your logs. To view your logs goto Views>Logs, it will show you the response you receive from Api.

Use generated json object instead d3.json

I missed a lot of time that to resolve this problem but unlucky. I know how to render d3 tree with external file, but how to do that with generated object. I'm getting Json object thru this code:
$.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
.then(function (a, b) {
return $.extend(a[0], b[0]);
})
.then(function (data) {
var json = JSON.stringify(data);
console.log('['+ json +']');
and have added json to d3.json
treeJSON = d3.json(json, function (error, treeData) {
so whole part of code looks like:
function load() {
$.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
.then(function (a, b) {
return $.extend(a[0], b[0]);
})
.then(function (data) {
var json = JSON.stringify(data);
console.log('['+ json +']');
// Get JSON data
treeJSON = d3.json(json, function (error, treeData) {
the most interesting part is that console log self defined such as right string:
[{"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]}]
but I'm still getting an error:
GET http://localhost:63342/testMerg/%7B%22text%22:%22Alas%22,%22icon%22:%22…SH%22%7D]%7D,%7B%22text%22:%22CDISC%22%7D,%7B%22text%22:%22BRIDG%22%7D]%7D 404 (Not Found)
I've tried to use string method from some example which I found somewhere here:
.then(function (data) {
var json = JSON.stringify(data);
// Get JSON data
treeData = JSON.parse( data );
but got an error
Uncaught SyntaxError: Unexpected token o
so I give up... could anybody help me?
The problem arises because data is an Object and your trying to parse the object. But JSON.parse function expects a string as the parameter.
You can either directly assign treeData = data. (No need for parsing).
Or else you should try stringifying the object and then parse the stringified json.
var json = JSON.stringify(data);
treeData = JSON.parse(json);
var data = {"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]};
//treeData = data;
json = JSON.stringify(data);
console.log(JSON.parse(json));

UrlFetch put method using Google Apps Script

Have tried many options to update a product in ECWID using Google Apps Script UrlFetchApp.fetch() put method but not succeeded. Following are the different ways that I've written the code and tested, but am getting different type of errors.
I guess, am missing some small thing, which am not able to figure it out. Please help me to fix this issue.
API: ECWID Products API (http://kb.ecwid.com/w/page/25285101/Product%20API#RESTAPIMethodupdateaproduct)
Method: PUT (to update the product details)
Sample Code 1:-
function updateProducts(){
var products_authkey = "xxxxxxxx";
try{
var url ="https://app.ecwid.com/api/v1/xxxxx/product?id=xxxxxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var options ={method:"put",ContentType:"application/json",payload:payload};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
}catch(e){
Browser.msgBox(e);
}
}
Error:-
"{ "error": "OTHER", "errorMessage": "Error parsing JSON: A JSONObject text must begin with '{' at character 0" }"
Version 2:-
Tried converting the object to json stringify, but the same error.
function updateProducts_version2(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product?id=xxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var payload_json = Utilities.jsonStringify(payload);
var options ={method:"put",ContentType:"application/json",payload:payload_json,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
Error:-
"{ "error": "OTHER", "errorMessage": "Error parsing JSON: A JSONObject text must begin with '{' at character 0" }"
Version 3:- (Tried passing secure_auth_key using Authorization in headers)
function updateProducts_version3(){
try{
var url ="https://app.ecwid.com/api/v1/xxxxx/product?id=xxxxx";
var payload = {price:62755};
var headers = {Authorization: 'xxxxxxx'};
var options = {headers:headers,method:"put",ContentType:"application/json",payload:payload};
var options ={method:"put",ContentType:"application/json",payload:payload,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
Error:-
{ "error": "OTHER", "errorMessage": "API key not found in request parameters" }
Also to note that, I've tried using DevHttpClient chrome plugin, it's updating properly.
Which means that there's some problem the way we're using UrlFetch. Please help me in fixing this issue...
Thanks in advance...
Credentials are needed to test this, so that's up to you. You probably need to both stringify & encode the payload. You also had incorrect capitalization on contentType, which you could check with UrlFetchApp.getRequest().
function updateProducts_version2a(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product?id=xxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var payload_json = encodeURIComponent(JSON.stringify(payload));
var options ={method:"put",contentType:"application/json",payload:payload_json,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
This next version seemed to work - by suppressing the price change and using a store's ID, it mimicked a product 'get', according to the docs you referenced. This time, the error message might be indicating some level of success: "This Ecwid account doesn't have access to Ecwid API. Please, consider upgrading it."
You'll notice that the URL has been separated out, with the basic header info of product ID and auth key together.
function updateProducts_version4(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product";
var payload = encodeURIComponent(JSON.stringify({
price:62755
}));
var headers = {id:'xxxx',
secure_auth_key: 'xxxxxxx'
};
var options = {
headers:headers,
method:"put",
contentType:"application/json",
muteHttpExceptions:true,
payload:payload
};
var request = UrlFetchApp.getRequest(url, options); // Debug: check what would be fetched
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var respHeaders = result.getHeaders(); ///
debugger;
}catch(e){
Logger.log(e);
//Browser.msgBox(e);
}
}
Without your creds, that's as far as I can take it... tell us how that works for you.

Categories