0

I am trying to run this code but it creates error.

import json
import requests
import pprint
data = []
with open('data.txt') as o1:
  for line in o1:
    data.append(json.loads(line))
    print(data)
    print(" \n")
print(data)
url = 'http://xyz.abcdfx.in/devicedata'
body_json=json.dumps(data)
headers = {'Content-Type':'application/json'}
d = requests.post(url, data = body_json, headers=headers)
pprint.pprint(d.json())

it shows

Value Error: No json object could be Decoded

I am new to programming and not able to figure out what is the problem.

5
  • Does it throw that error only when started from your crontab? Commented Jun 6, 2017 at 8:30
  • no it throws this error whenever i run this script Commented Jun 6, 2017 at 8:31
  • i'm sorry i think the title of this question is not right Commented Jun 6, 2017 at 8:33
  • At boot time? Maybe networking isn't up yet? Commented Jun 6, 2017 at 8:37
  • Btw, show us output of this script. Commented Jun 6, 2017 at 8:38

2 Answers 2

1

It seems like you are trying to parse the json file line by line, but the json objects may (and usually are) span more than one line. You need to have the entire file in order to parse it:

 with open('data.txt') as o1:
      data = json.loads(o1.read()) # read ALL the file and parse. no loops
 print(data)
Sign up to request clarification or add additional context in comments.

4 Comments

i tried this code but it again throw a Error :Value Error: Extra Data:
@Aaron.0 can you open 'data.txt' in any external json reader? It seems like the file is "not purely" json(?)
its json alright it runs well when there is only single data in 'data.txt' but throws error when there are more than that
@Aaron.0 who writes data.txt? why are there several "json data" in there?
0

i solved my problem using this:

data =[]
with open('data.txt') as f:
   for line in f:
      data = json.loads(line)
      print(data)
      url = 'http://xyz.abcdfx.cn/devicedata'
      body_json=json.dumps(data)
      headers = {'Content-Type':'application/json'}
      d = requests.post(url, data = body_json, headers=headers)
      pprint.pprint(d.json())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.