SyntaxError: Unexpected number when pulling JSON data. Why it happens? - google-apps-script

I am trying to pull the type JSON data from "0", but I'm getting a SyntaxError. In postman, part of the returned data looks like this:
var array = {
"catalogs": {
"add": {
"0": {
"type": 'catalog',
"id": '2027528',
"date_create": '1637310194',
"date_modify": '1637310194',
"created_by": '7382229',
"modified_by": '7382229',
"catalog_id": '8241',
"name": '',
"deleted": '0',
"custom_fields": {
"0": {
"id": '912743',
"name": 'Статус',
"values": {
"0": {
"value": 'Создан',
"enum": '4197277'
}
},
"code": 'BILL_STATUS'
},
"1": {
"id": '912747',
"name": 'Плательщик',
"values": {
"0": {
"value": {
"name": 'TEST+TEST',
"entity_id": '63836888',
"entity_type": 'contacts'
}
}
},
"code": 'PAYER'
},
"2": {
"id": '912753',
"name": 'Позиции+счета',
"values": {
"0": {
"value": {
"sku": '',
"description": '1111',
"unit_price": '1111',
"unit_type": 'шт',
"quantity": '1',
"discount": {
"type": 'amount',
"value": '0'
},
"vat_rate_id": '0',
"vat_rate_value": '20',
"bonus_points_per_purchase": '0',
"external_uid": ''
}
}
},
"code": 'ITEMS'
},
"3": {
"id": '912755',
"name": 'Комментарий',
"values": {
"0": {
"value": '1111'
}
},
"code": 'BILL_COMMENT'
},
"4": {
"id": '912757',
"name": 'Стоимость',
"values": {
"0": {
"value": '1111'
}
},
"code": 'BILL_PRICE'
}
},
"created_at": '1637310194',
"updated_at": '1637310194'
}
}
},
"account": {
"_links": {
"self": 'https://amocrm.ru'
},
"subdomain": 'mylogoped',
"id": '24809335'
}
};
When I try to use the code, I get an error (SyntaxError: Unexpected number)
var myDat = testOne.catalogs.add.0.type;
Found a solution in one of the posts, but it does not work, an error also comes out
for (let i = 0; i < testOne.catalogs.add.0.length; i++) {
var type = testOne.catalogs.add.0[i].type;
sheet.getRange(lastRow + 1, 5).setValue(type);
}
Found a solution here SyntaxError: Unexpected number when pulling JSON data but it doesn't work because SyntaxError: Unexpected token '['
for (let i = 0; i < testOne.catalogs.add.["0"].length; i++) {
var type = testOne.catalogs.add.["0"][i].type;
sheet.getRange(lastRow + 1, 5).setValue(type);
}
Please tell me how I can take data from the "0" array, everything behind it is pulled like this
var myData = testOne.account.subdomain;

You have no array in the JSON data.
It is an object with nested objects. Also the .["0"] syntax is incorrect.
You could do something like the following to iterate:
var keys = Object.keys(testOne.catalogs.add);//array of keys
for (let i = 0; i < keys.length; i++) {
var type = testOne.catalogs.add[keys[i]].type;
// ...do something
}
But it will not guarantee the order of items to be the same as you see in the data because of how the objects work. If order is important then you can sort the keys array accordingly.

Related

Remove duplicate objects in JSON array with jq based on specific criteria

I have the following data where I want entire objects removed based on duplicate values of the "run" key, while keeping the object with the largest "startTime" number:
{
"data": {
"results": [
{
"event": {
"biking": {
"startTime": 12,
"id": "a",
"run": "x"
}
},
"displayName": "Alex"
},
{
"event": {
"biking": {
"startTime": 10,
"id": "b",
"run": "x"
}
},
"displayName": "Adam"
},
{
"event": {
"biking": {
"startTime": 11,
"id": "c",
"run": "y"
}
},
"displayName": "Aaron"
}
]
}
}
I've been trying to finagle unique with jq but can't quite get what I want. My intended result is this:
{
"data": {
"results": [
{
"event": {
"biking": {
"startTime": 12,
"id": "a",
"run": "x"
}
},
"displayName": "Alex"
},
{
"event": {
"biking": {
"startTime": 11,
"id": "c",
"run": "y"
}
},
"displayName": "Aaron"
}
]
}
}
I was trying to use unique because I want to keep only 1 of each "run": ids where in a larger list I might have three x, two y, and four z. I'd want to keep one x, y, and z in this case based on the largest "startTime".
Here's a straightforward jq solution:
.data.results |=
(group_by(.event.biking.run)
| map(max_by(.event.biking.startTime)))
It uses group_by to group by "run", and then max_by to select the desired event.
Here's how it can be done using reducer.
const input = {
"data": {
"results": [{
"event": {
"biking": {
"startTime": 12,
"id": "a",
"run": "x"
}
},
"displayName": "Alex"
},
{
"event": {
"biking": {
"startTime": 10,
"id": "b",
"run": "x"
}
},
"displayName": "Adam"
},
{
"event": {
"biking": {
"startTime": 11,
"id": "c",
"run": "y"
}
},
"displayName": "Aaron"
}
]
}
};
const output = {
data: {}
};
output.data.results = Object.values(input.data.results.reduce((r, o) => {
r[o.event.biking.run] =
(r[o.event.biking.run] &&
r[o.event.biking.run].event.biking.startTime > o.event.biking.startTime) ? r[o.event.biking.run] : o
return r
}, {}));
console.log(output);
Credits -> https://stackoverflow.com/a/56901839/8057127
This would work
const result = [
...new Map(
obj.data.results.map((item) => [item["event"]["biking"]["run"], item])
).values()
];
DEMO
This is based on helprjs removeDuplicates.

How can we parse inner node of json response in Flutter app?

I'm having this response
"countryitems": [
{
"1": {
"ourid": 1,
"title": "Afghanistan",
"code": "AF",
},
"2": {
"ourid": 2,
"title": "Albania",
"code": "AL",
},
"3": {
"ourid": 3,
"title": "Algeria",
"code": "DZ", },
"4": {
"ourid": 4,
"title": "Angola",
"code": "AO",
}
}
]
For question, I've put only 4 nodes where actually I've 150 around of nodes. I'm not getting how can I parse to get country names?
Here is a possible solution. You have to decode the response with jsonDecode and generating a map out of the response. If you iterate through the map, you can access the inner nodes.
import 'dart:convert';
var jsonString =
"""
{
"countryitems": [
{
"1": {
"ourid": 1,
"title": "Afghanistan",
"code": "AF"
},
"2": {
"ourid": 2,
"title": "Albania",
"code": "AL"
},
"3": {
"ourid": 3,
"title": "Algeria",
"code": "DZ"
},
"4": {
"ourid": 4,
"title": "Angola",
"code": "AO"
}
}
]
}
""";
void main() {
Map<String, dynamic> obj = json.decode(jsonString)['countryitems'][0];
// print out all country names in obj
for(int i = 1; i <= obj.length; i++) {
print(obj['$i']['title']);
}
}
'dart:convert' is good for simple cases.
But when you need true flexibility and less boilerplate, I'd suggest to use this library instead https://github.com/k-paxian/dart-json-mapper

How to check if a key exists in a nested JSON object in node?

I've got the following JSON being sent to the server from the browser:
{
"title": "Testing again 2",
"abstract": "An example document",
"_href": "http://google.com",
"tags": [ "person" ],
"attributes": [ {
"id": 1,
"type": "TEXT",
"data": "test"
} ],
"sections": [ {
"id": 1,
"type": "LIST",
"data": [ {
"revision": 124,
"text": "test"
} ]
} ]
}
I need to make sure that the keys "_href", "id" and "revision" are not in the object anyplace at any level.
I found this but it doesn't quite work.
I searched npms.io and found has-any-deep which you can use after JSON.parse ing the JSON.
you need to parse json then check into the data
var str = '{
"title": "Testing again 2",
"abstract": "An example document",
"_href": "http://google.com",
"tags": [ "person" ],
"attributes": [ {
"id": 1,
"type": "TEXT",
"data": "test"
} ],
"sections": [ {
"id": 1,
"type": "LIST",
"data": [ {
"revision": 124,
"text": "test"
} ]
} ]
}';
var jsonObj = JSON.parse(str);
if ( typeof jsonObj._href == 'undefined') {
// check
}
A simple but not 100% foolproof solution would be to parse the JSON to string, and just search for your keys:
var a = JSON.stringify(JSONObject);
var occurs = false;
['"_href"', '"id"', '"version"'].forEach(function(string) {
if(a.indexOf(string) > -1) occurs = true;
});
The issue of course, is if there are values that match
'_href', 'id', 'version' in your JSON. But if you want to use native JS, I guess this is a good bet.
var a = {
"title": "Testing again 2",
"abstract": "An example document",
"tags": [ "person" ],
"attributes": [ {
"type": "TEXT",
"data": "test"
} ],
"sections": [ {
"type": "_href asdad",
"data": [ {
"text": "test"
} ]
} ]
},
b = {
"title": "Testing again 2",
"abstract": "An example document",
"_href": "http://google.com",
"tags": [ "person" ],
"attributes": [ {
"id": 1,
"type": "TEXT",
"data": "test"
} ],
"sections": [ {
"id": 1,
"type": "LIST",
"data": [ {
"revision": 124,
"text": "test"
} ]
} ]
},
aJson = JSON.stringify(a),
bJson = JSON.stringify(b);
var occursa = false, occursb = false;
['"_href"', '"id"', '"version"'].forEach(function(string) {
if(aJson.indexOf(string) > -1) { occursa = true};
});
['"_href"', '"id"', '"version"'].forEach(function(string) {
if(bJson.indexOf(string) > -1) { occursb = true};
});
console.log("a");
console.log(occursa);
console.log("b");
console.log(occursb);
You could use the optional second reviver parameter to JSON.parse for this:
function hasBadProp(json) {
let badProp = false;
JSON.parse(json, (k, v) => {
if ([_href", "id", "revision"].includes(k)) badProp = true;
return v;
});
return badProp;
}

Merge and save in json files nodejs

I'd like to add JSON object of a json file into another one.
Here is an example :
{
"HOUSES": {
"1": {
"NAME": "House1",
"PEOPLE": {},
"ID": 1
},
"2": {
"NAME": "House2",
"PEOPLE": {},
"ID": 2
},
"3": {
"NAME": "House3",
"PEOPLE": {},
"ID": 3
}
}
}
And people object :
{
"1": {
"NAME": "People1"
},
"2": {
"NAME": "People2"
},
"3": {
"NAME": "People3"
}
}
Now I'd like to add the people object into House1.
I tried that :
var extend = require('util')._extend;
var obj1 = house.PEOPLE; //var content : {}
var obj2 = extend(people, obj1); //var people content people object
This code replace all house1 by the people object. How can I add people object in the sublevel PEOPLE of house1?
I tried with object-assign too, and I have the same problem.
Thanks !
You can do it by:
HOUSES.1.PEOPLE = PEOPLEOOBJ;
Where PEOPLEOBJ is :
PEOPLEOBJ = {
"1": {
"NAME": "People1"
},
"2": {
"NAME": "People2"
},
"3": {
"NAME": "People3"
}
}

Linq to Json using Like Clause

I've got an MVC 3 web app and am returning a JSON object which I would like to use Linq against to limit the result returned to the client jquery.
The Json response takes the following structure:
{
"Data": {
"Items": [
{
"Result": {
"Id": "e2ba4912-c387-4f54-b55e-06742a6858db",
"Name": "SomeOtherSetting",
"Value": "500",
"Archived": false
},
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting2",
"Value": "600",
"Archived": false
},
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting3",
"Value": "700",
"Archived": false
}
}]
}
}
....
I need to return or grab just the json items that have a Name like 'Setting' for example. In the example, this would return just the 2 Json nodes.
My Linq is very limited and what I have is: Settings is where the Json response is stored.
NewtonSoft.Json.Linq.JObject data = NewtonSoft.Json.Linq.JObject.Parse(Settings);
var result = from p in data["Data"]["Items"].Children()
where (p["Result"]["Name"].Contains("Expenses.Help.Tip"))
select new { Name = (string)p["Result"]["Name"], Value = (string)p["Result"]["Value"] };
When I run this I get nothing in my result. Can anyone help and tell me what I'm doing wrong?
Thanks.
Well, I'm not a Json specialist, but I think your Json structure has some problems.
I tried an online parser, and parsing took only the third result... (try to copy past your code in the left window, and look at JS eval.
Instead of
"Items": [
{
"Result": {
},
"Result": {
},
"Result": {
}
}]
you should have each element of Items array (each 'Result') into {}.
"Items": [
{
{"Result": {
}
},
{"Result": {
}
},
{"Result": {
}
}]
I got it to work by changing your Json file to
{
"Data": {
"Items": [
{
"Result": {
"Id": "e2ba4912-c387-4f54-b55e-06742a6858db",
"Name": "SomeOtherSetting",
"Value": "500",
"Archived": false
}
},
{
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting2",
"Value": "600",
"Archived": false
}
},
{
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting3",
"Value": "700",
"Archived": false
}
}]
}
}
using
var data = JObject.Parse(test)["Data"]["Items"].Children()
.Where(m => m["Result"]["Name"].Value<string>().Contains("Setting"))
.Select(m => new
{
Name = m["Result"]["Name"].Value<string>(),
Value = m["Result"]["Value"].Value<int>()
})
.ToList();