I get back json from the server, I want to make it an array and just to test it will work I do
JSON.parse(response.data.blocks)
I get this:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at contentblocks.js?KHWUmpg:87149
at <anonymous>
How do I convert blocks to array so I can do this:
let blocks = response.data.blocks.sort(function(a,b){
var x = a.order < b.order? -1:1
return x
})
I got an error that sort did not exist, so I figured I need to make blocks an array so I can sort them.
This is what server sends back
{
"status": "success",
"blocks": {
"0": {
"id": 50,
"content_id": 25,
"type": "title-block-template",
"content": "yeah",
"content_type": null,
"template_block_id": 1,
"user_id": null,
"meta": null,
"created_at": "2017-08-13 17:27:53",
"updated_at": "2017-08-13 17:27:53",
"order": 1,
"settings": [
{
"id": 12,
"key": "order",
"value": "1",
"type": "integer",
"created_at": "2017-08-13 17:17:51",
"updated_at": "2017-08-13 17:17:51",
"pivot": {
"settingable_id": 50,
"setting_id": "12"
}
}
]
},
"1": {
"id": 51,
"content_id": 25,
"type": "images-block-template",
"content": "[]",
"content_type": null,
"template_block_id": 9,
"user_id": null,
"meta": null,
"created_at": "2017-08-13 17:27:53",
"updated_at": "2017-08-13 17:27:53",
"order": 3,
"settings": [
{
"id": 19,
"key": "order",
"value": "3",
"type": "integer",
"created_at": "2017-08-13 17:26:19",
"updated_at": "2017-08-13 17:30:24",
"pivot": {
"settingable_id": 51,
"setting_id": "19"
}
}
]
}
}
}
Sorting the properties of an object
Think of it not as sorting the object, but extracting the properties (into an array) and sorting them by property name.
Let's say your original object (the one you listed out at the bottom of your question) is called server_return_object.
Extract the blocks into an object using
blocks = server_return_object.blocks;
Now we need the keys ("0", "1", etc) of the blocks. Extract them using Object.keys().
block_keys = Object.keys(blocks);
Then we can create an array, with one element for each block. The easiest way is the .map() function, whose takes a list of items and performs a function on them.
block_array = block_keys.map( key => blocks[key] );
You now have in block_array an array of blocks, which you can then sort in any way you like. For example, to sort by the created_at you can use
block_array.sort(function(a,b){return a.created_at > b.created_at } )
Change the function inside the sort(), to return whatever criterion you want to sort on. If it is a simple sort on one of the properties, you can make the criterion, as shown above, a test for greater than (or less than, to sort the other way). More complex orderings are also possible, using multiple criteria.
It may already be parsed!
Two clues.
Already an object
Your display of what the server gives is already an object. It has a property "blocks" that could well be what you are after.
The unexpected token "o"
This is the error you get from JSON.parse when you feed an object into it, instead of a string.
Try this:
x={hello:3};
JSON.parse(x);
Related
This is a JSON snip that is created in WooCommerce by a plugin that adds some metadata. I cannot change the formatting of this JSON because it is generated by a plugin. The problem is that the keys and the values are added in a weird way. I am iterating through the line_items and statically referencing this data which I don't want to do, I would like to know if there is a smart way to reference for example:
"key": "_cpo_product_id",
"value": "3572",
if this was formatted correctly it would be: "_cpo_product_id": "3572" and not have "value" as a key, and it would be accessed by: foo.line_items[i]._cpo_product_id
but with this configuration I am a bit lost, I am sure there is an easy way to find the value for a specific key. I am doing this on Google app scripts, but a solution in JavaScript should suffice.
JSON snip:
"line_items": [
{
"id": 749,
"name": "Dune",
"product_id": 3572,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "149.54",
"subtotal_tax": "31.40",
"total": "149.54",
"total_tax": "31.40",
"taxes": [
{
"id": 24,
"total": "31.403148",
"subtotal": "31.403148"
}
],
"meta_data": [
{
"id": 11919,
"key": "_cpo_product_id",
"value": "3572",
"display_key": "_cpo_product_id",
"display_value": "3572"
},
{
"id": 11920,
"key": "_add-to-cart",
"value": "3572",
"display_key": "_add-to-cart",
"display_value": "3572"
},
I have a large json data that I have to parse and get object out of the following Json string. I added just top part of that large json data. I tried to parse it by
let obj = JSON.parse(this.state.data);
it doesn't work, it breaks with this msg "SyntaxError: Unexpected token L in JSON at position 0".
If I get the console.log by console.log(JSON.stringify(this.state.data, null, 2)); and try to validate output by online JSON validator, it says it is valid JSON data. Could you please tell me how can I parse it?
{
"content": [
{
"_id": 1,
"name": "Warehouse A",
"location": {
"lat": 47.13111,
"long": -61.54801
},
"cars": {
"location": "West wing",
"vehicles": [
{
"model": "GX",
"price": 27395.26,
"licensed": false,
"_id": 15,
"make": "Lexus",
"year_model": 2005,
"date_added": "2017-11-12T00:00:00.000+00:00"
},
{
"model": "Q",
"price": 6103.4,
"licensed": false,
"_id": 9,
"make": "Infiniti",
"year_model": 1995,
"date_added": "2017-11-13T00:00:00.000+00:00"
},
.........xxxxxx continue
Your variable this.state.data is not a JSON. It's a Javascript Object, just like JSON, So, Why not just use let obj = this.state.data;
In order to hash (sha1) a JSON and to compare the resulting hash to a given one, I need a String which is exactly the same as the one that has been used to create the given hash.
Then, my stringified JSON must have different indentation for sub nodes of the JSON :
I want this js object :
{id:4,name:'patrick',roles:[{id:1,name:'admin'},{id:2,name:'author'}]}
to be stringified like that :
"{
"id": "4",
"name": "patrick",
"roles": [
{"id":1,"name":"admin"},
{"id":2,"name":"author"}
]
}"
JSON.stringify(obj,null,4) gives me something very near from the solution but not exactly :
"{
"id": 4,
"name": "patrick",
"roles": [
{
"id": 1,
"name": "admin"
},
{
"id": 2,
"name": "author"
}
]
}"
I'm trying with the second argument of JSON.stringify but can not reach my goal :'(
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
My data on server is in the form of JSON array of objects. If I want to print the first object, how can I access its first object? Format of data is:
[
{
"eventId": "8577",
"datasetId": "34",
"nodeId": "8076",
"typeId": "4",
"type": "TempAndHum",
"status": "Temp : 35, Hum : 83",
"datasetName": "test active set",
"mode": "shared",
"xmlFragment": "Absent",
"gpsLat": "-23.549999",
"gpsLong": "-46.633301",
"contributor": "SanatIITD",
"addedOn": "2015-04-21 08:03:16",
"updatedOn": "2015-04-21 08:03:16"
},
{
"eventId": "8576",
"datasetId": "34",
"nodeId": "8076",
"typeId": "4",
"type": "TempAndHum",
"status": "Temp : 34, Hum : 81",
"datasetName": "test active set",
"mode": "shared",
"xmlFragment": "Absent",
"gpsLat": "-23.549999",
"gpsLong": "-46.633301",
"contributor": "SanatIITD",
"addedOn": "2015-04-21 08:03:11",
"updatedOn": "2015-04-21 08:03:11"
},
{
"eventId": "8575",
"datasetId": "34",
"nodeId": "8076",
"typeId": "4",
"type": "TempAndHum",
"status": "Temp : 33, Hum : 80",
"datasetName": "test active set",
"mode": "shared",
"xmlFragment": "Absent",
"gpsLat": "-23.549999",
"gpsLong": "-46.633301",
"contributor": "SanatIITD",
"addedOn": "2015-04-21 08:03:05",
"updatedOn": "2015-04-21 08:03:05"
},
]
I tried with data[0], but end up with printing "[". I tried with JSON.stringify also and then split with "," but that gives me first element of the object, not the whole first object. I need to print the whole first object which is within the curly braces. Is there any way so that I can access like array and by doing document.getElementById("Id")=myData[0], so that I don't need to print all elements within the curly braces separately. Please suggest me some solution. Thanks in advance.
use var dataArray = JSON.parse(dataString) first,
your data is a string at the moment.
Then use dataArray[0]
In a collection i need to set the value to one of attributes, but i cant find the way how do it
products.models[i].set({'category.name':'some_value'})
the rest api looks like this
{
"category": {
"id": 3,
"name": "Drink",
"icon": "staging/main/category/icon-drinks.png"
},
"id": 1,
"name": "Sugar54",
"dashboard": 1,
"last_buy": "2013-10-02",
"price": "102",
"buy_period": 7
},
How do i do that ?
If you have complex nested models, I suggest you take a look at BackboneRelational.
Otherwise in your case, you should be fine with
products.models[i].get('category').name = 'some_value';
supposing that category is a normal object.