I have tried to access an element of the json structure but can't. I have tried the following.
I am using the npm package json-query to extract part of the bigger JSON object.
var rslt = jsonQuery('results[**][* status=active]', {
data: response
});
var make = JSON.stringify(rslt.value[0]["parms"]["make"])
Bu this does not work, I have also tried to get the following data from the JSON:
var img = JSON.stringify(rslt.value[0]["photos"]["1"]["320x240"]);
var subtitle = JSON.stringify(rslt.value[0]["parms"]["price"]["1"]) + ' EUR';
This is the JSON data I am working with:
{
"value":[
{
"id":7038271775,
"user_id":1307227,
"status":"active",
"title":"",
"url":"https://www.autovit.ro/anunt/nissan-navara-ID7GjS0w.html",
"created_at":"2017-01-06 17:49:35",
"valid_to":"2017-02-03 17:56:16",
"description":"Data inmatriculare: 02.03.2015.\r\n4x4 \r\nABS \r\nAer conditionat \r\nComputer de bord \r\nGeamuri electrice \r\nInchidere centralizata \r\nJante aliaj \r\nRadio CD \r\nServodirectie \r\nVolan multifunctional",
"category_id":29,
"region_id":46,
"city_id":24691,
"city":{
"ro":"Voluntari",
"en":"Voluntari"
},
"coordinates":{
"latitude":44.49192877,
"longitude":26.12458706,
"radius":0,
"zoom_level":16
},
"advertiser_type":"business",
"contact":{
"person":"LeasePlan Outlet Center",
"phone_numbers":[
"0753312151"
]
},
"params":{
"make":"nissan",
"model":"navara",
"year":2014,
"mileage":16785,
"engine_capacity":2500,
"vin":"VSKCVND40U0566467",
"fuel_type":"diesel",
"gearbox":"manual",
"transmission":"all-wheel-lock",
"particle_filter":"0",
"green_tax":"1",
"damaged":"0",
"body_type":"suv",
"door_count":4,
"color":"white",
"metallic":"0",
"pearl":"0",
"matt":"0",
"rhd":"0",
"features":[ ],
"price":{
"0":"price",
"1":15900,
"currency":"EUR",
"gross_net":"net"
},
"vat":"1",
"financial_option":"1",
"leasing_concession":"0",
"date_registration":"2014-1-01",
"registered":"1",
"original_owner":"1",
"no_accident":"0",
"service_record":"0",
"historical_vehicle":"0",
"tuning":"0"
},
"photos":{
"1":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_1_1080x720.jpg",
"732x488":"https://img40.autovit.ro/images_autovitro/820558483_1_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_1_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_1_148x110.jpg"
},
"2":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_2_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_2_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_2_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_2_148x110.jpg"
},
"3":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_3_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_3_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_3_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_3_148x110.jpg"
},
"4":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_4_1080x720.jpg",
"732x488":"https://img40.autovit.ro/images_autovitro/820558483_4_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_4_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_4_148x110.jpg"
},
"5":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_5_1080x720.jpg",
"732x488":"https://img41.autovit.ro/images_autovitro/820558483_5_732x488.jpg",
"320x240":"https://img41.autovit.ro/images_autovitro/820558483_5_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_5_148x110.jpg"
},
"6":{
"1080x720":"https://img40.autovit.ro/images_autovitro/820558483_6_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_6_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_6_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_6_148x110.jpg"
},
"7":{
"1080x720":"https://img40.autovit.ro/images_autovitro/820558483_7_1080x720.jpg",
"732x488":"https://img41.autovit.ro/images_autovitro/820558483_7_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_7_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_7_148x110.jpg"
},
"8":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_8_1080x720.jpg",
"732x488":"https://img41.autovit.ro/images_autovitro/820558483_8_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_8_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_8_148x110.jpg"
},
"9":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_9_1080x720.jpg",
"732x488":"https://img40.autovit.ro/images_autovitro/820558483_9_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_9_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_9_148x110.jpg"
},
"10":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_10_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_10_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_10_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_10_148x110.jpg"
},
"11":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_11_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_11_732x488.jpg",
"320x240":"https://img41.autovit.ro/images_autovitro/820558483_11_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_11_148x110.jpg"
}
},
"image_collection_id":820558483,
"last_update_date":"2017-01-24 18:00:26",
"new_used":"used"
}
],
"is_last_page":false,
"is_first_page":true,
"current_page":1,
"total_pages":33,
"current_elements":1,
"total_elements":33
}
I don't know what excatly "json-query" does but I think you can extract any JSON part safely like this;
function dig(input, key) {
var keys = (""+ key).split("."), key = keys.shift();
if (!keys.length) {
return input[key];
}
return dig(input[key], keys.join("."));
}
// here that gives me already without any error thrown >> https://img42.autovit.ro/images_autovitro/820558483_1_320x240.jpg
var p = dig(rslt, "results.0.photos.1.320x240");
console.log(p);
// this is same with
console.log(rslt.results[0].photos[1]["320x240"]);
Credits: https://github.com/yay-couch/couch-js/blob/master/couch/util/util.js#L46
i'm not sure how its not working, the only problem i see with your code is you mistaken by writing params and you write parms
Related
I'm a bit confused about some expected behavior regarding NodeLists, and was hoping that someone could point me in the right direction.
So I have a hidden input element whose value attribute holds a json string with a bunch of s3 upload data. It looks like this:
<input
name="uppyResult"
type="hidden"
value="[
{
"successful":[
{
"source":"Dashboard",
"id":"uppy-screen/shot/2021/07/15/at/4/00/02/pm/png-10-10-1d-1d-10-10-1e-1e-10-1e-image/png-165186-1626390007842",
"name":"Screen Shot 2021-07-15 at 4.00.02 PM.png",
"extension":"png",
"meta":{
"relativePath":null,
"name":"Screen Shot 2021-07-15 at 4.00.02 PM.png",
"type":"image/png",
"key":"cache/4870f1e1d9f075c7397b3422f101f7e4.png",
"Content-Disposition":"inline; filename=\"Screen Shot 2021-07-15 at 4.00.02 PM.png\"; filename*=UTF-8''Screen%20Shot%202021-07-15%20at%204.00.02%20PM.png",
"Content-Type":"image/png",
"policy":"eyJleHBpcmF0aW9uIjoiMjAyMS0wOC0yN1QyMzoyMDo0M1oiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJmcmFjdGlvbmNsdWItZGV2MiJ9LHsia2V5IjoiY2FjaGUvNDg3MGYxZTFkOWYwNzVjNzM5N2IzNDIyZjEwMWY3ZTQucG5nIn0seyJDb250ZW50LURpc3Bvc2l0aW9uIjoiaW5saW5lOyBmaWxlbmFtZT1cIlNjcmVlbiBTaG90IDIwMjEtMDctMTUgYXQgNC4wMC4wMiBQTS5wbmdcIjsgZmlsZW5hbWUqPVVURi04JydTY3JlZW4lMjBTaG90JTIwMjAyMS0wNy0xNSUyMGF0JTIwNC4wMC4wMiUyMFBNLnBuZyJ9LHsiQ29udGVudC1UeXBlIjoiaW1hZ2UvcG5nIn0sWyJjb250ZW50LWxlbmd0aC1yYW5nZSIsMCwxMDQ4NTc2MF0seyJ4LWFtei1jcmVkZW50aWFsIjoiQUtJQTNKRVpaRkFOTzNCNlI0VE8vMjAyMTA4MjcvdXMtd2VzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LHsieC1hbXotYWxnb3JpdGhtIjoiQVdTNC1ITUFDLVNIQTI1NiJ9LHsieC1hbXotZGF0ZSI6IjIwMjEwODI3VDIyMjA0M1oifV19",
"x-amz-credential":"whatever/20210827/region/s3/aws4_request",
"x-amz-algorithm":"AWS4-HMAC-SHA256",
"x-amz-date":"20210827T222043Z",
"x-amz-signature":"8478e24c985b7517399dd3278591e283584403c666983b1d6900c3d4c0b594d5"
},
"type":"image/png",
"data":{},
"progress":{
"uploadStarted":1630102841653,
"uploadComplete":true,
"percentage":100,
"bytesUploaded":167201,
"bytesTotal":167201,
"postprocess":null
},
"size":165186,
"isRemote":false,
"remote":"",
"preview":"blob:https://example.com/ab73e53f-7b2c-4a77-aade-07f216b31d27",
"xhrUpload":{
"method":"post",
"formData":true,
"endpoint":"https://example.s3.region.amazonaws.com",
"metaFields":[
"key","Content-Disposition","Content-Type","policy","x-amz-credential","x-amz-algorithm","x-amz-date","x-amz-signature"
],
"headers":{}
},
"response":{
"status":204,
"body":{
"location":null
},
"uploadURL":null
},
"uploadURL":null,"isPaused":false
}
],
"failed":[],
"uploadID":"cksux56ic00013h63szerkigt"
},
{
"successful":[
{
"source":"Dashboard",
"id":"uppy-blackdog/parkerbright/servitude2017/jpg-2v-2v-1e-image/jpeg-24872-1613012190277",
"name":"blackdog_parkerbright_servitude2017.jpg",
"extension":"jpg",
"meta":{
"relativePath":null,
"name":"blackdog_parkerbright_servitude2017.jpg",
"type":"image/jpeg",
"key":"cache/da42d10f2b1f47b004654b257df07a01.jpg",
"Content-Disposition":"inline; filename=\"blackdog_parkerbright_servitude2017.jpg\"; filename*=UTF-8''blackdog_parkerbright_servitude2017.jpg",
"Content-Type":"image/jpeg",
"policy":"eyJleHBpcmF0aW9uIjoiMjAyMS0wOC0yN1QyMzoyMTozMVoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJmcmFjdGlvbmNsdWItZGV2MiJ9LHsia2V5IjoiY2FjaGUvZGE0MmQxMGYyYjFmNDdiMDA0NjU0YjI1N2RmMDdhMDEuanBnIn0seyJDb250ZW50LURpc3Bvc2l0aW9uIjoiaW5saW5lOyBmaWxlbmFtZT1cImJsYWNrZG9nX3BhcmtlcmJyaWdodF9zZXJ2aXR1ZGUyMDE3LmpwZ1wiOyBmaWxlbmFtZSo9VVRGLTgnJ2JsYWNrZG9nX3BhcmtlcmJyaWdodF9zZXJ2aXR1ZGUyMDE3LmpwZyJ9LHsiQ29udGVudC1UeXBlIjoiaW1hZ2UvanBlZyJ9LFsiY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjBdLHsieC1hbXotY3JlZGVudGlhbCI6IkFLSUEzSkVaWkZBTk8zQjZSNFRPLzIwMjEwODI3L3VzLXdlc3QtMS9zMy9hd3M0X3JlcXVlc3QifSx7IngtYW16LWFsZ29yaXRobSI6IkFXUzQtSE1BQy1TSEEyNTYifSx7IngtYW16LWRhdGUiOiIyMDIxMDgyN1QyMjIxMzFaIn1dfQ==",
"x-amz-credential":"whatever/20210827/region/s3/aws4_request",
"x-amz-algorithm":"AWS4-HMAC-SHA256",
"x-amz-date":"20210827T222131Z",
"x-amz-signature":"a17970d6b111ed0acb535342433626ec7d277fd6364517bb3ee9c02de529f0d7"
},
"type":"image/jpeg",
"data":{},
"progress":{
"uploadStarted":1630102891533,
"uploadComplete":true,
"percentage":100,
"bytesUploaded":26864,
"bytesTotal":26864,
"postprocess":null
},
"size":24872,
"isRemote":false,
"remote":"",
"preview":"blob:https://example.com/79066114-d51b-4ef4-b62a-af8ac80ae617",
"xhrUpload":{
"method":"post",
"formData":true,
"endpoint":"https://example.s3.region.amazonaws.com",
"metaFields":[
"key","Content-Disposition","Content-Type","policy","x-amz-credential","x-amz-algorithm","x-amz-date","x-amz-signature"
],
"headers":{}
},
"response":{
"status":204,
"body":{
"location":null
},
"uploadURL":null
},
"uploadURL":null,
"isPaused":false
}
],
"failed":[],
"uploadID":"cksux68zv00033h63tzjc85kg"
}
]"
>
When I log document.getElementsByName("uppyResult") to console, it shows up as a NodeList. Which apparently is sort of like an array, but not? The data I need to access in this NodeList takes a click and a scroll to get to - I simply expand the input and scroll to defaultValue.
What I need is access to every successful object in this NodeList. There can be one or many. Note that this one has two.
My last attempt at doing this same thing was botched because I misunderstood what I was trying to do. Though the selected answer did solve the problem as I phrased it, what I needed was to perform the same action for more than just the initial [0] item. Each uploaded batch of files occupies an index in this array, and I need to get all of them.
The old code from that answer is:
if (reason === 'removed-by-user') {
const preParsedData = document.getElementsByName("uppyResult")[0].value //this is the problem, i think - i need *all* the elements in the array/NodeList
const parsedData = JSON.parse(preParsedData)
const toRemove = file.id
parsedData.forEach(item => {
Object.values(item).forEach(array => {
if (!Array.isArray(array))
return;
const index = array.findIndex(elm => elm.id === toRemove)
if (index > -1)
array.splice(index, 1)
});
if (item.successful.length === 0)
delete item.successful
delete item.failed
delete item.uploadID
});
console.log(parsedData)
document.getElementsByName("uppyResult")[0].value = JSON.stringify(parsedData)
}
})
In case if you "need all the elements in the array/NodeList" you have to go through all nodes with other forEach call.
So, it will looks like:
const inputEls = document.getElementsByName("uppyResult")
inputEls.forEach((node) => {
// here run the code you already have
const preParsedData = node.value
const parsedData = JSON.parse(preParsedData)
....
}
Before you parse the data in value it has to be a valid JSON string. For that, you have to replace every instance of " by " using the .replace() method so that it becomes a valid JSON string to be parsed.
const preParsedData = document.getElementsByName("uppyResult")[0].value.replace(""","\"");
const parsedData = JSON.parse(preParsedData);
console.log(parsedData);
<html>
<head>
<title>Title</title>
</head>
<body>
<input name="uppyResult" type="hidden" value="[
{
"successful":[
{
"source":"Dashboard",
"id":"uppy-screen/shot/2021/07/15/at/4/00/02/pm/png-10-10-1d-1d-10-10-1e-1e-10-1e-image/png-165186-1626390007842",
"name":"Screen Shot 2021-07-15 at 4.00.02 PM.png",
"extension":"png",
"meta":{
"relativePath":null,
"name":"Screen Shot 2021-07-15 at 4.00.02 PM.png",
"type":"image/png",
"key":"cache/4870f1e1d9f075c7397b3422f101f7e4.png",
"Content-Disposition":"inline; filename=\"Screen Shot 2021-07-15 at 4.00.02 PM.png\"; filename*=UTF-8''Screen%20Shot%202021-07-15%20at%204.00.02%20PM.png",
"Content-Type":"image/png",
"policy":"eyJleHBpcmF0aW9uIjoiMjAyMS0wOC0yN1QyMzoyMDo0M1oiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJmcmFjdGlvbmNsdWItZGV2MiJ9LHsia2V5IjoiY2FjaGUvNDg3MGYxZTFkOWYwNzVjNzM5N2IzNDIyZjEwMWY3ZTQucG5nIn0seyJDb250ZW50LURpc3Bvc2l0aW9uIjoiaW5saW5lOyBmaWxlbmFtZT1cIlNjcmVlbiBTaG90IDIwMjEtMDctMTUgYXQgNC4wMC4wMiBQTS5wbmdcIjsgZmlsZW5hbWUqPVVURi04JydTY3JlZW4lMjBTaG90JTIwMjAyMS0wNy0xNSUyMGF0JTIwNC4wMC4wMiUyMFBNLnBuZyJ9LHsiQ29udGVudC1UeXBlIjoiaW1hZ2UvcG5nIn0sWyJjb250ZW50LWxlbmd0aC1yYW5nZSIsMCwxMDQ4NTc2MF0seyJ4LWFtei1jcmVkZW50aWFsIjoiQUtJQTNKRVpaRkFOTzNCNlI0VE8vMjAyMTA4MjcvdXMtd2VzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LHsieC1hbXotYWxnb3JpdGhtIjoiQVdTNC1ITUFDLVNIQTI1NiJ9LHsieC1hbXotZGF0ZSI6IjIwMjEwODI3VDIyMjA0M1oifV19",
"x-amz-credential":"whatever/20210827/region/s3/aws4_request",
"x-amz-algorithm":"AWS4-HMAC-SHA256",
"x-amz-date":"20210827T222043Z",
"x-amz-signature":"8478e24c985b7517399dd3278591e283584403c666983b1d6900c3d4c0b594d5"
},
"type":"image/png",
"data":{},
"progress":{
"uploadStarted":1630102841653,
"uploadComplete":true,
"percentage":100,
"bytesUploaded":167201,
"bytesTotal":167201,
"postprocess":null
},
"size":165186,
"isRemote":false,
"remote":"",
"preview":"blob:https://example.com/ab73e53f-7b2c-4a77-aade-07f216b31d27",
"xhrUpload":{
"method":"post",
"formData":true,
"endpoint":"https://example.s3.region.amazonaws.com",
"metaFields":[
"key","Content-Disposition","Content-Type","policy","x-amz-credential","x-amz-algorithm","x-amz-date","x-amz-signature"
],
"headers":{}
},
"response":{
"status":204,
"body":{
"location":null
},
"uploadURL":null
},
"uploadURL":null,"isPaused":false
}
],
"failed":[],
"uploadID":"cksux56ic00013h63szerkigt"
},
{
"successful":[
{
"source":"Dashboard",
"id":"uppy-blackdog/parkerbright/servitude2017/jpg-2v-2v-1e-image/jpeg-24872-1613012190277",
"name":"blackdog_parkerbright_servitude2017.jpg",
"extension":"jpg",
"meta":{
"relativePath":null,
"name":"blackdog_parkerbright_servitude2017.jpg",
"type":"image/jpeg",
"key":"cache/da42d10f2b1f47b004654b257df07a01.jpg",
"Content-Disposition":"inline; filename=\"blackdog_parkerbright_servitude2017.jpg\"; filename*=UTF-8''blackdog_parkerbright_servitude2017.jpg",
"Content-Type":"image/jpeg",
"policy":"eyJleHBpcmF0aW9uIjoiMjAyMS0wOC0yN1QyMzoyMTozMVoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJmcmFjdGlvbmNsdWItZGV2MiJ9LHsia2V5IjoiY2FjaGUvZGE0MmQxMGYyYjFmNDdiMDA0NjU0YjI1N2RmMDdhMDEuanBnIn0seyJDb250ZW50LURpc3Bvc2l0aW9uIjoiaW5saW5lOyBmaWxlbmFtZT1cImJsYWNrZG9nX3BhcmtlcmJyaWdodF9zZXJ2aXR1ZGUyMDE3LmpwZ1wiOyBmaWxlbmFtZSo9VVRGLTgnJ2JsYWNrZG9nX3BhcmtlcmJyaWdodF9zZXJ2aXR1ZGUyMDE3LmpwZyJ9LHsiQ29udGVudC1UeXBlIjoiaW1hZ2UvanBlZyJ9LFsiY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjBdLHsieC1hbXotY3JlZGVudGlhbCI6IkFLSUEzSkVaWkZBTk8zQjZSNFRPLzIwMjEwODI3L3VzLXdlc3QtMS9zMy9hd3M0X3JlcXVlc3QifSx7IngtYW16LWFsZ29yaXRobSI6IkFXUzQtSE1BQy1TSEEyNTYifSx7IngtYW16LWRhdGUiOiIyMDIxMDgyN1QyMjIxMzFaIn1dfQ==",
"x-amz-credential":"whatever/20210827/region/s3/aws4_request",
"x-amz-algorithm":"AWS4-HMAC-SHA256",
"x-amz-date":"20210827T222131Z",
"x-amz-signature":"a17970d6b111ed0acb535342433626ec7d277fd6364517bb3ee9c02de529f0d7"
},
"type":"image/jpeg",
"data":{},
"progress":{
"uploadStarted":1630102891533,
"uploadComplete":true,
"percentage":100,
"bytesUploaded":26864,
"bytesTotal":26864,
"postprocess":null
},
"size":24872,
"isRemote":false,
"remote":"",
"preview":"blob:https://example.com/79066114-d51b-4ef4-b62a-af8ac80ae617",
"xhrUpload":{
"method":"post",
"formData":true,
"endpoint":"https://example.s3.region.amazonaws.com",
"metaFields":[
"key","Content-Disposition","Content-Type","policy","x-amz-credential","x-amz-algorithm","x-amz-date","x-amz-signature"
],
"headers":{}
},
"response":{
"status":204,
"body":{
"location":null
},
"uploadURL":null
},
"uploadURL":null,
"isPaused":false
}
],
"failed":[],
"uploadID":"cksux68zv00033h63tzjc85kg"
}
]">
</body>
</html>
Hello I am trying to figure out how to get the "changes" value from
{ data: { sequenceStart: 1613141716565, symbol: 'KCS-BTC', changes: { asks: [Array], bids: [] }, sequenceEnd: 1613141716565 }, subject: 'trade.l2update', topic: '/market/level2:KCS-BTC', type: 'message' }
The data is stored in let data = JSON.parse(msg)
I have tried console.log(data.data.changes) but get undefined, im lost because console.log(data.data) seems to get me part way there but not when I add .changes?
Can you check my code below.
I think your msg is not formated correctly , you can compare with my code
<body >
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
var msg = '{"data": { "sequenceStart": "1613141716565", "symbol": "KCS-BTC", "changes": { "asks":[["0","0","1613141798456"]],"bids":[]}, "sequenceEnd": 1613141716565 }, "subject": "trade.l2update", "topic": "/market/level2:KCS-BTC", "type": "message" }';
var data = JSON.parse(msg);
console.log(data.data.changes);
var msg1 = '{"sequenceStart":1613141798456,"symbol":"KCS-BTC","changes":{"asks":[["0","0","1613141798456"]],"bids":[]},"sequenceEnd":1613141798456}';
var data1 = JSON.parse(msg1);
console.log(data1.changes);
});
</script>
</body>
I have a instance of Vue.js that make a fetch GET request and i want to display all the data using v-for but i can access the field that i want inside the jsonBody requisition.
My instance of vue.js:
var pedidosTable = new Vue({
el: '#pedidosTable',
data: function(){
return{
listOfDi: [],
listOfStep1: []
}
},
created: function(){
const req = fetch("http://localhost:4242/api/v1/dis").then(response =>{
return response.json();
}).then(jsonBody =>{
this.listOfDi = jsonBody;
});
},
methods:{
},
});
my HTML:
<tr v-for="item of listOfDi">
<td>{{ item.DI.Step1[0].nomeDoCliente }}</td>
</tr>
My json in the fetch request:
[
{
"_id":"5f4608e4516d5c137e9d40e7",
"DI":{
"Step1":[
{
"codigoCliente":"56777",
"operacao":"PRÓPRIA",
"tipoDeOperacao":"TRADING",
"lucro":"REAL",
"beneficioIpi":"NÃO",
"consumidor":"P. JURÍDICA",
"rateio":"PESO",
"nomeDoCliente":"Submarino",
"dolarDi":4.4359,
"dolarCambio":4.5
}
],
"Step2":[
{
"id":{
"oid":"5f232394ac7e930548107d16"
},
"produto":"cadeira de rodas",
"ncm":"467.987",
"descricao":"cadeira de rodas teste",
"cliente_id":{
"oid":"5f21e23eac7e9305490f9424"
},
"aliqII":0.2,
"aliqIpi":0,
"aliqPis":0.21,
"aliqCofins":0.0965,
"pesoUnitario":0.43,
"unitario":0.88,
"dumping":0,
"cubagemUnitario":0,
"quantidade":33,
"icmEstadoDestino":0,
"mvaAjustado":0,
"markup":0.12,
"selected":true,
"url":"http://localhost:3000/produtos/5f232394ac7e930548107d16.json"
},
{
"id":{
"oid":"5f232c61ac7e930a6f8ea06a"
},
"produto":"Bicicleta",
"ncm":"456.879",
"descricao":"Bicicleta caloi",
"cliente_id":{
"oid":"5f21e23eac7e9305490f9424"
},
"aliqII":0.2,
"aliqIpi":0,
"aliqPis":0.21,
"aliqCofins":0.0965,
"pesoUnitario":0.43,
"unitario":0.78,
"dumping":0,
"cubagemUnitario":0,
"quantidade":44,
"icmEstadoDestino":0,
"mvaAjustado":0,
"markup":0.12,
"selected":true,
"url":"http://localhost:3000/produtos/5f232c61ac7e930a6f8ea06a.json"
}
],
"Step3":[
{
"freteInternacional":1790.36,
"capatazia":384.35,
"siscomex":260.1,
"marinhaMercante":2076.97,
"outrasDespesasAduaneiras":1000
}
],
"Step4":[
{
"armazenagemZonaPrimaria":2986,
"diferencaFreteInternacional":158.09,
"despachante":1835.68,
"liStep4":53.53,
"taxasBl":844.05,
"tarifaCambial":250,
"multa":0,
"taxaExpediente":250,
"freteAoCliente":1194,
"debitoIcms":0.04,
"pagEfetivo":0.04,
"pagDesembaraco":0.01,
"descontoComercial":0.01,
"debitoPIS":0.0165,
"debitoCofins":0.076,
"IR":0.25,
"CSLL":0.09
}
]
}
},
{
"_id":"5f460d55f46a2b160079f9a8",
"DI":{
"Step1":[
{
"codigoCliente":"98978",
"operacao":"PRÓPRIA",
"tipoDeOperacao":"TRADING",
"lucro":"REAL",
"beneficioIpi":"NÃO",
"consumidor":"P. JURÍDICA",
"rateio":"PESO",
"nomeDoCliente":"Black & Decker",
"dolarDi":4.4359,
"dolarCambio":4.5
}
],
"Step2":[
{
"id":{
"oid":"5f077925ac7e9319ff7d1c6b"
},
"produto":"cafeteira",
"ncm":"9878.7389",
"descricao":"cafeteira capsula",
"cliente_id":{
"oid":"5f0775e8ac7e9319ff7d1c68"
},
"aliqII":0.2,
"aliqIpi":0,
"aliqPis":0.21,
"aliqCofins":0.0965,
"pesoUnitario":0.43,
"unitario":0.78,
"dumping":0,
"cubagemUnitario":0,
"quantidade":12,
"icmEstadoDestino":0,
"mvaAjustado":0,
"markup":0.12,
"selected":true,
"url":"http://localhost:3000/produtos/5f077925ac7e9319ff7d1c6b.json"
}
],
"Step3":[
{
"freteInternacional":1790.36,
"capatazia":384.35,
"siscomex":260.1,
"marinhaMercante":2076.97,
"outrasDespesasAduaneiras":1000
}
],
"Step4":[
{
"armazenagemZonaPrimaria":2986,
"diferencaFreteInternacional":158.09,
"despachante":1835.68,
"liStep4":53.53,
"taxasBl":844.05,
"tarifaCambial":250,
"multa":0,
"taxaExpediente":250,
"freteAoCliente":1194,
"debitoIcms":0.04,
"pagEfetivo":0.04,
"pagDesembaraco":0.01,
"descontoComercial":0.01,
"debitoPIS":0.0165,
"debitoCofins":0.076,
"IR":0.25,
"CSLL":0.09
}
],
}
}
]
How can i acess and display the field nomeDoCliente inside the Step1 array in my v-for list?
when i run solr, I got output like that, but i need show "response":{"numFound":4,"start":0,"maxScore":0.21373023,"docs"} line and all lines have id
this is my html
<div id="response">
<pre class="syntax language-{{lang}} content"><code ng-bind-html="response.data | highlight:lang | unsafe "></code></pre>
<div id="result">
<a ng-show="response.data" id="url" class="address-bar addressblock" ng-href="{{url}}">{{hostPortContext}}{{url}}</a>
</div>`
this is my query.js that In connection with the result (here "data" is result object)
var url = Query.url(params);
Query.query(params, function(data) {
$scope.lang = $scope.query.wt;
if ($scope.lang == undefined || $scope.lang == '') {
$scope.lang = "json";
}
$scope.response = data ;
$scope.filterdata=$filter('uppercase') ($scope.response);
$scope.url = url;
$scope.hostPortContext = $location.absUrl().substr(0,$location.absUrl().indexOf("#"));
});`
and got this result
{
"responseHeader":{
"zkConnected":true,
"status":0,
"QTime":21,
"params":{
"q":"sed",
"_":"1580536766390"}},
"response":{"numFound":4,"start":0,"maxScore":0.21373023,"docs":[
{
"id":"/home/sama/sama_installer/masternode",
"attr_stream_size":["15732"],
"attr_x_parsed_by":["org.apache.tika.parser.DefaultParser",
"org.apache.tika.parser.txt.TXTParser"],
"attr_stream_content_type":["application/octet-stream"],
"attr_content_encoding":["ISO-8859-1"],
"attr_resourcename":["/home/sama/sama_installer/masternode"],
"content_type":"application/x-sh; charset=ISO-8859-1",
"language":"en",
...
"_version_":1657306606928396288,
"content":" #!/bin/bash\n#installetion sama project on master\n#cheeke exits sama
{
"id":"/home/sama/sama_installer/start.sh",
"attr_stream_size":["290"],
"attr_x_parsed_by":["org.apache.tika.parser.DefaultParser",
"org.apache.tika.parser.txt.TXTParser"],
"attr_stream_content_type":["application/octet-stream"],
"attr_content_encoding":["ISO-8859-1"],
"attr_resourcename":["/home/sama/sama_installer/start.sh"],
"content_type":"application/x-sh; charset=ISO-8859-1",
"content":" #!/bin/bash\nstart-all.sh\nt=$(cat /var/sama/nodelist)\nfor i in ,
"language":"en",
"content_type_type_s":"application",
"content_type_subtype_s":"x-sh",
"url_ss":["start-all.sh",
"zkServer.sh"],
"_version_":1657306608004235264}]
}}
I am Assuming data realated to your Question. You Can fetch data in following manner. If it return undefined it means there is not parameter named 'id' else 'id' is present
var data = {
"responseHeader": {
"zkConnected": true,
"status": 0,
"id": 101,
"QTime": 21
},
"response": {
"numFound": 4,
"start": 0,
"maxScore": 0.21373023,
"id": 102
},
"response1": {
"numFound": 4,
"start": 0,
"maxScore": 0.21373023
}
}
console.log(data.response)
console.log(data.responseHeader["id"])
console.log(data.response["id"])
console.log(typeof(data.response1["id"]) == "undefined") //This way you can check if id is present or not.
if (typeof(data.response["id"]) != "undefined") {
console.log(data.response)
}
I have a Library angularJS application and a JSON Data file that contains an array of book's information like this
[
{
"name" : "test1",
"pages": 0,
"author": "author1",
"year": 1940,
"section": "history",
"current": 0,
"description": "bla bla bla",
"bookUrl": "data/book.pdf"
},
{
"name" : "test1",
"pages": 0,
"author": "author1",
"year": 1940,
"section": "history",
"current": 0,
"description": "bla bla bla",
"bookUrl": "data/book.pdf"
}
]
"current" is for the current page of the current book that i'm reading
and there is a "next" and "prev" buttons in the reading view
when i press "next" it adds "+1" to the "current" num page
the question is (How to send this +1 to the "current" in JSON file with PHP?)
I have this PHP code :
<?php
$jsonString = file_get_contents('library.json');
$data = json_decode($jsonString, true);
$data[0]['current'] = 3;
$newJsonString = json_encode($data);
file_put_contents('library.json', $newJsonString);
?>
See the ($data[0]) is for the index of the first book, how do i send to PHP the index of the current book so it updates the "current" data of the current book?
Here is the "next" function :
scope.goNext = function() {
if (scope.pageToDisplay >= pdfDoc.numPages) {
return;
}
scope.pageNum = parseInt(scope.pageNum) + 1;
$http.get("data/insert.php")
.success(function(data, status, headers, config) {
console.log("data inserted successfully");
});
};
And here is the reading Controller :
app.controller('read', ['$scope','books', '$routeParams',function($scope,books, $routeParams) {
books.success(function(data){
$scope.book = data[$routeParams.bookId]
$scope.pdfUrl = data[$routeParams.bookId].bookUrl;
$scope.pdfName = data[$routeParams.bookId].name;
});
//the pdf viewer options
//$scope.pdfUrl = 'data/tohfa12.pdf';
$scope.scroll = 0;
$scope.loading = 'Loading file please wait';
$scope.getNavStyle = function(scroll) {
if(scroll > 100) {
return 'pdf-controls fixed';
} else {
return 'pdf-controls';
}
};
$scope.onError = function(error) {
console.log(error);
};
$scope.onLoad = function() {
$scope.loading = '';
};
$scope.onProgress = function(progress) {
console.log(progress);
};
$scope.currentBookIndex = parseInt($routeParams.bookId);
}]);
I know it's complicated but i really need that , thanks.
How do you expect your application to behave?
You need to send the bookId and the pageNum with your request!
scope.goNext = function() {
if (scope.pageToDisplay >= pdfDoc.numPages) {
return;
}
scope.pageNum = parseInt(scope.pageNum) + 1;
$http.get("data/insert.php", {
param : {
bookId: $scope.bookId,
pageNum: $scope.pageNum
}
})
.success(function(data, status, headers, config) {
console.log("data inserted successfully");
});
};
BTW. By REST design a GET http request should never change a resource. GET is for READING. If you want to update a resource you should use POST, PUT or DELETE