forumisto
Posts: 386
Joined: Fri Mar 16, 2012 8:41 am

problems working with json

Thu Sep 15, 2016 10:27 am

Hello

I have a JSON file that if I open it with xed there are characters shown as square with numbers inside.
I can read the file as text but I can not work with it as json object, the method json.loads(txt) fails. The error message is: ValueError: No JSON object could be decoded

How can I use it as json object?

Thank you.

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: problems working with json

Thu Sep 15, 2016 11:12 am

Can you post either
a. A link to your code
b. Your code in between [code][/code] tags

It is going to be very difficult to help you debug the problem without seeing your code.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

User avatar
B.Goode
Posts: 10191
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: problems working with json

Thu Sep 15, 2016 11:25 am

The argument to json.loads() should be a string, not a reference to a file.

Maybe you are calling the wrong method to inspect the data?

Examples here: https://docs.python.org/3/library/json.html

forumisto
Posts: 386
Joined: Fri Mar 16, 2012 8:41 am

Re: problems working with json

Thu Sep 15, 2016 11:46 am

txt is a string

I can't paste the content of the string because there is an error when I try submit (SQL ERROR [ mysqli ]; Incorrect string value: '\xF0\x9F\x8E\xAC&q...' for column 'post_text' at row 1 [1366])

The code only is:

Code: Select all

import json

data = open('list.w3u').read()

data = json.loads(data)

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: problems working with json

Thu Sep 15, 2016 12:12 pm

Try using this snippet of code to see if you can read in the file

Code: Select all

import json
from pprint import pprint

with open('<NAMEOFYOURFILE>') as data_file:    
    data = json.load(data_file)

pprint(data)
Failing that, it might be an issue with the encoding of your file. Have a look at this post on Stack Exchange for tips of how to read file with different encoding
http://stackoverflow.com/questions/2835 ... -in-python

For example

Code: Select all

with open('data.json', encoding='utf-8') as data_file:
    data = json.loads(data_file.read())
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Return to “Python”