I try to search long and hard to find my answers and almost never ask questions if I can help it. but it's 5am and I've been working on this project for quite a few months now and I'm stuck.
THE PROBLEM
I have a JSON file saved on my local server which has the following layout:
*Note I've cut down the JSON file to remove the bloat and focus on exactly what I'm trying to extract here.
{
"count": 74,
"results": [
{
"listing_id": 151323205,
"Images": [
{
"url_75x75": "https:\/\/img1.etsystatic.com\/013\/0\/7566894\/il_75x75.459599049_hptl.jpg",
},
]
}
],
"params": {
"limit": "1",
"shop_id": "username",
},
}
THE CODE
Now I've managed to iterate through all the other stuff like 'listing_id' & 'Images' but it appears the 'shop_id' is outside of the scope of my foreach command and inside the 'params' portion?
foreach($results->results as $product){
$products[$i]['url_75x75'] = $product->Images[0]->url_75x75;
$i++;
}
I'm not super PHP savvy so If you can dumb it down just a bit? It's probably something very simple for you guys and I'd like to learn what I'm doing wrong and how to do it right.
This isn't the full code like I stated so if you need more insight please ask. I didn't want to bombard people with a bunch of my keyboard slapping coding skills :)
Thank you so much! I love SO!
You should be able to get the shop id with the following code:
$shop_id = $results->params->shop_id;
You can use this inside the foreach loop if you want to (though its value will not change of course).
$results is probably your whole object, which contains all the data that was in the JSON. $results->results reads only the "results" part inside the JSON, so the loop only iterates over what is in there.
To read the shop id, you can just read:
echo $results->params->shop_id;
Params is on the same level as results so in your for each where you are looking at $results->results, you are not including params, you can nest your for each like
Foreach ($results as $result) {
Foreach ($result->results){}
Foreach ($result->params){}
}
Related
To keep this short, i m working on a small discord bot. The bot is supposed to grab a servers banlist and then put it into its database. The problem is, to make a bulk insert, you appearently need an array that is stuctured like this
[
["blah 1", "bluh 1"],
["blah 2", "bluh 2"]
]
The problem that i m facing is, it distorts the formatting of the array for some reason
[
["blah 1", "bluh 1"],
[
"blah 1",
"bluh 1"
],
]
This is the code i use to create the array
list.forEach(element => {
if(element.reason === null){ var reason = "No reason Given"}else{ var reason = element.reason}
var userArray = [
element.user.id,
element.user.username,
element.user.discriminator,
reason,
element.user.bot
]
banArray.push(userArray)
})
Okay, to put this short again (its 4:11 am here right now, and i m lacking a lot of sleep). I found the problem i was having. I tried to use an array in my prepared statement while putting the unknown value into brackets.
queryStmt = "INSERT INTO tbl_bans (dtUserId, dtUserName, dtDiscriminator, dtReason, dtBot) VALUES (?)";
Notice the (?). The problem is, that i simply didnt look correctly at the code sample, and overlooked that there were no () around the ? in the sample.
I have a problem writing a query to extract a table out of the arrays from a json file: The problem is how to get the information of the array “clientPerformance” and then make them all in a normal sql table.
The file looks like this:
"clientPerformance":[
{
"name":"opportunity",
"clientProcess":{
"value":3620000.0,
"count":1.0,
"min":3620000.0,
"max":3620000.0,
"stdDev":0.0,
"sampledValue":3620000.0
},
"networkConnection":{
"value":10000.0,
"count":1.0,
"min":10000.0,
"max":10000.0,
"stdDev":0.0,
"sampledValue":10000.0
},
"receiveRequest":{
"value":9470000.0,
"count":1.0,
"min":9470000.0,
"max":9470000.0,
"stdDev":0.0,
"sampledValue":9470000.0
},
"sendRequest":{
"value":1400000.0,
"count":1.0,
"min":1400000.0,
"max":1400000.0,
"stdDev":0.0,
"sampledValue":1400000.0
},
"total":{
"value":14500000.0,
"count":1.0,
"min":14500000.0,
"max":14500000.0,
"stdDev":0.0,
"sampledValue":14500000.0
},
"url":"https://xxxx",
"urlData":{
"base":"/main.aspx",
"host":"xxxx",
"hashTag":"",
"protocol":"https"
}
}
]
I tried to use Get array elements method and other ways but I am never able to access to clientProcess, networkConnection.. elements
I tried to use for exampls this one:
Select
GetRecordPropertyValue(GetArrayElement(Input.clientPerformance, 0), 'name') AS Name,
GetRecordPropertyValue(GetArrayElement(Input.clientPerformance, 1), 'clientProcess.count') AS clientProcessCount,
FROM [app-insights-blob-dev] Input
I would appreciate any help :)
I slightly edited your query to return the clientProcessCount.
(I changed the array index from 1 to 0). Also make sure your JSON object starts with { and ends with }.
Select
GetRecordPropertyValue(GetArrayElement(Input.clientPerformance, 0), 'name') AS Name,
GetRecordPropertyValue(GetArrayElement(Input.clientPerformance, 0), 'clientProcess.count') AS clientProcessCount
FROM [app-insights-blob-dev] Input
For other examples to query complex objects with ASA, don't hesitate to look at this blog post.
I'm currently trying to do a bit of complex N1QL for a project I'm working on, theoretically I could do all of this processing in multiple N1QL calls and by parsing the results each time, however if possible I'd like for this to contained in one call.
What I would like to do is:
filter all documents that contain a "dataSync.test.id" field with more than 1 id
Read back all other ids in that list
Use that list to get other documents containing those ids
Get the "dataSync.test._channels" field for those documents (optionally a filter by docType might help parsing)
This would probably return a list of "dataSync.test._channels"
Is this possible in N1QL? It appears like it might be but I can't get the syntax right.
My data structures look a little like
{
"dataSync": {
"test": {
"_channels": [
"RP"
],
"id": [
"dataSync_user_1015",
"dataSync_user_1010",
"dataSync_user_1005"
],
"_lastUpdatedBy": "TEST"
}
},
...
}
{
"dataSync": {
"test": {
"_channels": [
"RSD"
],
"id": [
"dataSync_user_1010"
],
"_lastUpdatedBy": "TEST"
}
},
...
}
Yes. I think you can do all these.
Initial set of IDs with filtering can be retrieved as a subquery and then you can get subsquent documents by joins.
SELECT fulldoc
FROM (select meta().id as dockey from doc where a=1) as mydoc
INNER JOIN doc fulldoc ON KEYS mydoc.dockey;
There are optimizations that can be done here. Try the sequencing first to ensure you're get the job done.
I'm using jade templates for my templating system, passing a json file in as the jade locals via my gulpfile.js, but I can't seem to deep dive into the json. I feel like I'm overlooking something basic, but can't find an example online anywhere.
gulpfile.js:
Passes the json file into jade
gulp.task('html', function() {
gulp.src('./markup/*.jade')
.pipe(jade({
pretty: true,
locals: JSON.parse( fs.readFileSync('./markup/data/website_data.json', { encoding: 'utf8' }) )
}).on('error', gutil.log))
.pipe(gulp.dest('../'))
});
Then in my jade, I just pass the locals into a variable for the sake of readability.
- var employees = locals
And I can loop through json that is one level deep:
jade:
for employee in employees
if employee.Tier === 'Founder'
li
button(data-bio="#{employee.LastName.toLowerCase()}")
img(src="/public/img/employees/#{employee.FirstName.toLowerCase()}-#{employee.LastName.toLowerCase()}.jpg", alt="#{employee.FirstName} #{employee.LastName} | #{employee.Title}")
strong #{employee.FirstName} #{employee.LastName}
| #{employee.Title}
json:
[
{
"FirstName":"John",
"LastName":"Doe",
"Title":"Strategist",
"Tier":"Founder",
"Description":"",
"Email":"",
"Links":""
},
...
]
But that has only worked for me if the items I loop through are in the root, as soon as I make the json one level deeper, I can't get it to work based on the key. I want to make the json deeper so I can different sections of a site in it instead of just the employees.
[{
"employees": [
{
"FirstName":"Jason",
"LastName":"Bellinger",
"Title":"Lorem Ipsum",
"Tier":"",
"Description":"",
"Email":"",
"Links":""
},
...
]
}]
I tried a few different approaches to to dig into the json and have failed thus far.
ATTEMPT 1: adjust the variable call and keep the same loop
- var employees = locals.employees
And I get 'Cannot read property 'length' of undefined' in the terminal running $gulp watch
Also try:
- var employees = locals['employees']
to the same result.
ATTEMPT 2: don't use the var and call locals directly in my loop
for employee in locals.employees
AND
for employee in locals["employees"]
And I end up with the same error.
ATTEMPT 3:
keep the var and adjust the loop
- var employees = locals
...
for employee in employees
li #{employee.LastName}
Then I don't get an error in Terminal, but I don't get any content. It produces one empty li.
So then, I try to go a layer deeper in the loop with:
for employee in employees[0]
li #{employee.LastName}
AND
for employee in employees['employees']
li #{employee.LastName}
AND I still get no error and one empty li
I've parsed enough json in my day and jade seems simple enough, I have to be overlooking something basic. Someone please humble me.
I also dabbled in gulp-data, but I'm getting the data into jade with my approach, so I think it's my approach in jade...
You need to access the array inside you locals variable.
The length of local = 1 and that is the entire array of employees.
You'll need to set employees = to the array inside of the locals variable with:
"- var employees = locals[0].employees"
I knew it was something basic. I reverted everything back to the original setup and changed the var and this is working.
- var employees = locals[0]['employees']
Truth be told, I thought I already tried this, but went back and tried again...
I have a classic JSON problem, and i know that many post are asking about that...
But i doubt that the JSON i try to grab has a correct structure.
The files Begin like that :
[{
"time":"0-12h",
"articles":[
{
"id":1,
"domain_id":22,
"title":"Hi Guys"
}
{
"id":2,
"domain_id":17,
"title":"Hi everyone"
}
]
}]
I have try a lot of combinaison to echo the title :
$data = json_decode($json, true);
echo $data->articles;
Or
echo $data->articles->title;
Or
echo $data->articles[0]->title;
Nothing works... :(
Can you help me ?
Thanks !
The second argument true to json_decode() means it should create associative arrays rather than objects for {} in the JSON. So in addition to dealing with the indexed arrays as Explosion Pills points out, you also need to use array syntax to access the keyed elements:
$data[0]['articles'][0]['title']
If you want to be able to use -> syntax, leave out the second argument or set it to false.
I'm hoping the missing comma in the JSON is an error when transcribing to the question. If not, you also need to fix the code that creates the JSON in the first place.
$data itself is an array. Try
$data[0]->articles[0]->title;
Also the JSON is not valid (missing a comma before the second articles array element).
there is a comma , missing
}
,
{
json_decode with the second parameter true returns an array
print_r($data['articles']);
echo $data['articles'] would output Array