Poppy Cooke

Poppy Cooke

1548127798

JSON Parsing stops working when used with Flask on PythonAnywhere

I'm using Flask and PythonAnywhere to deploy a small new server which takes latitude/longitude arrays, sends this to the Bing Maps Snap-to-Road API which says that it would return a JSON file. However, the json.loads() always stops working ONLY when used on PythonAnywhere.

As of right now, I've tried the code on two local machines and it works fine. The PythonAnywhere instance is using Python 3.7, and I've tried the Bing Maps JSON code on both a Python 3.6 local machine and a Python 3.7 machine. I've even uploaded the file that I used for testing (not the entire server code, as that is fairly long), but the Bing Maps API code, onto PythonAnywhere and tested on their Python interpreter(both 3.7 and 3.6) and it seems to have worked fine, returning the two expected arrays.

import requests
lngArray = [array of longitudes stored as floats]
latArray = [array of latitudes stored as floats]
snappedLatArray = []
snappedLngArray = []

arrayLength = len(lngArray)
apiKey =“my-API-Key”
baseURL = “http://dev.virtualearth.net/REST/v1/Routes/SnapToRoad?points=
for i in range(0,arrayLength):
baseURL = baseURL+(str(latArray[i])[:9])+“,”+(str(lngArray[i])[:9])
if (i != (arrayLength - 1)):
baseURL = baseURL + “;”
elif(i == (arrayLength - 1)):
pass

finalURL = baseURL+“&interpolate=true&key=”+apiKey
print(finalURL)

c = requests.get(finalURL)
snappedPointsDict = c.json()
snappedPoints = snappedPointsDict[‘resourceSets’][0][‘resources’][0]
[‘snappedPoints’]
for x in snappedPoints:
snappedLat = x[‘coordinate’][‘latitude’]
snappedLng = x[‘coordinate’][‘longitude’]
snappedLatArray.append(snappedLat)
snappedLngArray.append(snappedLng)

On my machine and when run as a standalone program (such as the one above), it works flawlessly, and the snappedLatArray and snappedLngArray output arrays of latitudes and longitudes respectively. However, when run in a Flask environment, it fails, and in the error log it shows simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0) and the app stops working.

#python #json #flask

What is GEEK

Buddha Community

Zara Bryant

1548231646

Look at the contents of the response that you’re trying to parse so you can see why it’s not parsing as JSON.

Autumn  Blick

Autumn Blick

1593251880

JSON Parsing in Android - Step by Step Implementation

JSON Structures in Android

JSON uses two types of brackets that are as follows:

  • [] – To declare the elements of Array in JSON, they’re written in square brackets.
  • {} – To create JSON objects, the elements are written in curly brackets.

JSON has the following types of structures that are:

1. JSON Objects

The elements inside the curly brackets are known as Objects.

2. JSON Array

A list of values, known as Arrays.

3. JSON Key-Value

This data is stored as a pair of keys and values. Here the keys can be a name, a number for which the values can be Seema, 98767586 etc.

Why JSON Parsing in Android over XML?

Let us see some reasons for why to choose JSON over XML:

  • It is much easier and quicker with high performance
  • It can use arrays
  • Its libraries do not depend on other libraries
  • The codes written in JSON are short, clean and easy to understand
  • It is free to open use and open-source tool
  • In JSON value retrieval is easy
  • It has a fully automated way of serializing/deserializing JavaScript.
  • It is supported by many Ajax toolkits and most of the backend technologies.

Examples of XML and JSON

Let us see the code difference of JSON and XML files:

XML Example:

<?xml version= “1.0” encoding= “” ?>
<student>
        <student>
  <name> Sia Sharma</name>
  <city> Chandigarh</city>
         </student>
        <student>
  <name>Dimple D’souza</name>
  <city> Nagpur</city>
         </student>
      <student>
  <name>Anna Jones</name>
  <city> Mumbai</city>
         </student>
  </student>

JSON Example:

{ “students”: [
{ “name”: “Sia Sharma”, “city”: “Chandigarh”},
{ “name”: “Prachi D’Souza”, “city”: “Nagpur”},
{ “name”: “Annas Jones”, “city”: “Mumbai”}
]}

I hope the difference is all clear in front of you. This is how simple JSON is and how easily it could be understood.

#android tutorials #json parsing in android #json parsing in android example #json parsing in android step by step #json parsing with android #read json file android

Brandon  Adams

Brandon Adams

1625637060

What is JSON? | JSON Objects and JSON Arrays | Working with JSONs Tutorial

In this video, we work with JSONs, which are a common data format for most web services (i.e. APIs). Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

What is an API?
https://youtu.be/T74OdSCBJfw

JSON Google Extension
https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en

Endpoint Example
http://maps.googleapis.com/maps/api/geocode/json?address=13+East+60th+Street+New+York,+NY

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#jsons #json arrays #json objects #what is json #jsons tutorial #blondiebytes

Poppy Cooke

Poppy Cooke

1548127798

JSON Parsing stops working when used with Flask on PythonAnywhere

I'm using Flask and PythonAnywhere to deploy a small new server which takes latitude/longitude arrays, sends this to the Bing Maps Snap-to-Road API which says that it would return a JSON file. However, the json.loads() always stops working ONLY when used on PythonAnywhere.

As of right now, I've tried the code on two local machines and it works fine. The PythonAnywhere instance is using Python 3.7, and I've tried the Bing Maps JSON code on both a Python 3.6 local machine and a Python 3.7 machine. I've even uploaded the file that I used for testing (not the entire server code, as that is fairly long), but the Bing Maps API code, onto PythonAnywhere and tested on their Python interpreter(both 3.7 and 3.6) and it seems to have worked fine, returning the two expected arrays.

import requests
lngArray = [array of longitudes stored as floats]
latArray = [array of latitudes stored as floats]
snappedLatArray = []
snappedLngArray = []

arrayLength = len(lngArray)
apiKey =“my-API-Key”
baseURL = “http://dev.virtualearth.net/REST/v1/Routes/SnapToRoad?points=
for i in range(0,arrayLength):
baseURL = baseURL+(str(latArray[i])[:9])+“,”+(str(lngArray[i])[:9])
if (i != (arrayLength - 1)):
baseURL = baseURL + “;”
elif(i == (arrayLength - 1)):
pass

finalURL = baseURL+“&interpolate=true&key=”+apiKey
print(finalURL)

c = requests.get(finalURL)
snappedPointsDict = c.json()
snappedPoints = snappedPointsDict[‘resourceSets’][0][‘resources’][0]
[‘snappedPoints’]
for x in snappedPoints:
snappedLat = x[‘coordinate’][‘latitude’]
snappedLng = x[‘coordinate’][‘longitude’]
snappedLatArray.append(snappedLat)
snappedLngArray.append(snappedLng)

On my machine and when run as a standalone program (such as the one above), it works flawlessly, and the snappedLatArray and snappedLngArray output arrays of latitudes and longitudes respectively. However, when run in a Flask environment, it fails, and in the error log it shows simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0) and the app stops working.

#python #json #flask

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website

Hollie  Ratke

Hollie Ratke

1596800220

Complex JSON parsing with Ansible and JMESPath

JSON has become the lingua franca of the computer world for sharing information between applications. Just about anyone who writes code to interact with Web APIs or retrieve the results of an application will need to know how to parse JSON. Luckily, due to JSON’s popularity, it has wide support and there are many packages, like JMESPath, available to help parse complex JSON structures.

Frequently when I am deploying or updating infrastructure using Ansible I have to parse JSON results from a cloud provider or the output of a command like kubectl when interacting with Kubernetes. The output from these sources often contains a lot of information, parsing all of that information just to get what needed and transforming it into a usable format is often difficult.

In the following example output from kubectl get node node-name -o json , there isn’t an easy way to get the status for the type Ready using Ansible’s native JSON parsing without looping through the list.

{
  "conditions": [
              {
                  "status": "False",
                  "type": "NetworkUnavailable"
              },
              {
                 "status": "False",
                  "type": "MemoryPressure"
              },
              {
                  "status": "False",
                  "type": "DiskPressure"
              },
              {
                  "status": "False",
                  "type": "PIDPressure"
              },
              {
                 "status": "True",
                  "type": "Ready"
              }
  ]
}

However, Ansible has solved this problem by exposing the JMESPath JSON parsing library using the json_query filter.

In this example I will demonstrate how to use Ansible and JMESPath to parse complex JSON output and transform the results into a more usable format by using a key filter and zipping two JSON lists.


For this example, I am using OpenStack Heat to create an 8 node (3 MON nodes and 5 OSD nodes) Ceph cluster that will have Ceph installed using ceph-ansible. Since I am in the development and testing phase of this project, I am frequently creating and destroying the clusters. OpenStack Heat and Ansible do a good job on automating most of the creation and destroying steps, however there was still a manual step where I had to copy the hostnames and ip addresses for the nodes created by OpenStack Heat into Ansible’s inventory file. In order to fully automate the process, I had to capture the output from OpenStack Heat in Ansible so I could automatically generate the inventory file using an Ansible template.

To make the inventory file it mean converting this JSON:

{
    "stack_create.stack.outputs": [
        {
            "description": "Ceph osd management addresses",
            "output_key": "ceph_osd_management_addresses",
            "output_value": [
                "192.168.0.95",
                "192.168.0.101",
                "192.168.0.155",
                "192.168.0.161",
                "192.168.0.23"
            ]
        },
        {
            "description": "Ceph osd server names",
            "output_key": "ceph_osd_server_names",
            "output_value": [
                "ceph-osd-0",
                "ceph-osd-1",
                "ceph-osd-2",
                "ceph-osd-3",
                "ceph-osd-4"
            ]
        },
        {
            "description": "Ceph mon management addresses",
            "output_key": "ceph_mon_management_addresses",
            "output_value": [
                "192.168.0.117",
                "192.168.0.240",
                "192.168.0.44"
            ]
        },
        {
            "description": "Ceph mon server names",
            "output_key": "ceph_mon_server_names",
            "output_value": [
                "ceph-mon-0",
                "ceph-mon-1",
                "ceph-mon-2"
            ]
        }
    ]
}

Into the following inventory file:

[mons]
ceph-mon-0 ansible_host=192.168.0.117 
ceph-mon-1 ansible_host=192.168.0.240 
ceph-mon-2 ansible_host=192.168.0.44
[osds]
ceph-osd-0 ansible_host=192.168.0.95 
ceph-osd-1 ansible_host=192.168.0.101 
ceph-osd-2 ansible_host=192.168.0.155
ceph-osd-3 ansible_host=192.168.0.161
ceph-osd-4 ansible_host=192.168.0.23

In general, Ansible has good native parsing of JSON, however Ansible’s native JSON parsing cannot handle the case, like above, when you need to filter a list of JSON objects based on the value of a key that is in one of the JSON objects. For example, in the above JSON output, I want the list of ip address in the key output_value where output_key = ceph_mon_management_addresses. The best that can be done with Ansible’s native JSON parsing is stack_create.stack.outputs[2].output_value , but that would require the ceph_mon_management_addresses to always be the 3rd item in the list, which cannot be guaranteed.

Here is where Ansible’s json_query filter comes in. With JMESPath we can search a list of objects for a key value pair but return the value of another key in the same object. In practical terms for this example, we can search the list of objects for the object where output_key = ceph_mon_management_addresses and return the value of output_value. Here is the Ansible set_fact task using a JMESPath query to get the result:

- name: Create a list of mon ip addresses
  set_fact:
     mon_ips: "{{ stack_create | json_query(\"stack.outputs[?output_key == ‘ceph_mon_management_addresses’].output_value\") }}"

In this example, the search for the object that contains output_key == ‘ceph_mon_management_addresses’ is done using the JMESPath filter projection (?) with the statement from above. Then we append .output_value to return the value of the output_value key. The results will look like:

[
  [
    "192.168.0.117",
    "192.168.0.240",
    "192.168.0.44"
  ]
]

Since JMESPath is preserving the original format of the JSON, there are two nested lists, the list of objects and the list of ip addresses. We only want a list of ip addresses, therefore we can apply the JMESPath flatten projection to get the output we want. Simply add [] to the end of the statement like so:

- name: Create a list of mon ip addresses
  set_fact:
     mon_ips: "{{ stack_create | json_query(\"stack.outputs[?output_key == ‘ceph_mon_management_addresses’].output_value[]\") }}"

#parse #json #ansible #jmespath #parsing